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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
735f9bed2d8df7a6e4ab8b7f0394ce79c9da0967
|
ae0d7be8827e8983c926f48a5304c897dc32bbdc
|
/Gauche-tir/trunk/lib/tir04/session.scm
|
1ea7adc06e4b0b6e919ad57711e78b399e7b0fb6
|
[
"MIT"
] |
permissive
|
ayamada/copy-of-svn.tir.jp
|
96c2176a0295f60928d4911ce3daee0439d0e0f4
|
101cd00d595ee7bb96348df54f49707295e9e263
|
refs/heads/master
| 2020-04-04T01:03:07.637225 | 2015-05-28T07:00:18 | 2015-05-28T07:00:18 | 1,085,533 | 3 | 2 | null | 2015-05-28T07:00:18 | 2010-11-16T15:56:30 |
Scheme
|
EUC-JP
|
Scheme
| false | false | 14,676 |
scm
|
session.scm
|
;;; coding: euc-jp
;;; -*- scheme -*-
;;; vim:set ft=scheme ts=8 sts=2 sw=2 et:
;;; $Id$
;;; 概要:
;;; このモジュールは、セッション保持を行う為のクラスを作成する為の
;;; 枠組みを提供する。
;;; 実際にそういうクラスを作りたい時は、
;;; このクラスをベースクラスに指定する事になる。
;;; - セッションテーブルのエントリのkeyをsidと呼ぶ。
;;; 具体的には、sha1ダイジェスト値の16進文字列化された32文字の文字列になる。
;;; - セッションテーブルのエントリのvalueには、大抵の場合、あらゆる
;;; read/write invarianceを満たすオブジェクトを保存する事が出来る。
;;; -- モジュールによっては、それ以外のオブジェクトを保存できる場合もある。
;;; このモジュールが提供するセッションの概要:
;;; - セッションとは、タイムアウトによるGCもどきが付いた、
;;; (永続)テーブルのようなものとする。
;;; -- つまり、sidによってvalueを保存し、GCされない限りは取り出せるものとする。
;;; -- sidはcreate-session!によってのみ生成できる。
;;; これはsha1ダイジェストを16進文字列化した32文字の文字列になる。
;;; セキュリティ上の観点より、任意の文字列をkeyに使う手段は無いものとする。
;;; -- GCに回収されたsid/valueは、最初から存在しなかったものとして扱われる。
;;; --- 要するに、タイムアウトなのか最初から存在しなかったのか、
;;; 区別する手段は無いという事。
;;; 実際にセッションを使う場合の状況について:
;;; - セッションは通常、ログイン等を行い、ユーザの認証を行った後に、
;;; その認証状態を保持しているという証の割符として利用される。
;;; よって、(正しくvalueに対応する)sidを持つ=認証が行われた状態、となる為、
;;; 不正な手段によってセッションを発行できないようにする必要がある。
;;; 具体的には、ログイン完了時以外に新規セッションを作成できてはいけない。
;;; - また、このセッションの性格上、処理パターンは大体、以下の通りになる。
;;; -- sidを持たない。anonymousユーザとして処理を行う。
;;; (必要最小限の権限しか与えない、または、ログイン以外の権限を全く与えない)
;;; -- ログイン手続きを行い、sidを受け取る最中のanonymousユーザ。
;;; -- sidを持っている。ログイン済ユーザとして処理を行う。
;;; (必要に応じて権限を与える)
;;; - よって、大きく分けて、(正しくvalueに対応する)sid持ちと、それ以外の場合で
;;; 処理が大きく変わる為、以下のような方式で管理するのが良いと考えられる。
#|
(with-session
session-obj
sid ; 正しいsidまたは#f
(lambda (session-data) ; sidが不正、または、セッションが存在しない場合は#f
;; 新規にセッションを作成する
;; (session-dataが#fの時のみ実行可能。それ以外の場合はエラー例外を投げる)
(let1 new-sid (create-session! new-session-data)
;; セッションにデータを保存し、そのsidを受け取る
...)
;; セッションに保存したデータを更新する
(update-session! new-session-data)
;; セッションを削除する(ログアウト処理等で使う)
(remove-session!)
;; 尚、このprocが終了する際、
;; 内部でupdate-session!が行われていない場合であっても、
;; セッションへのアクセスが有効である事を示す為に、
;; 自動的にセッションのライフタイムが更新される。
...) ; このprocの返り値は、with-sessionの返り値になる
|#
;;; その他の仕様:
;;; - セッションに#fを保存しようとすると、セッションは削除される。
;;; -- しかし、セッションが存在しない場合はwith-sessionのprocには
;;; #fが渡されるので、挙動的には問題は無い筈。
;;; - 全く別の系列に属する複数のセッションマネージャは同時に利用可能だが、
;;; (但し、その場合にmethodを呼ぶ際には明示的に
;;; セッションマネージャを指定する必要がある)
;;; 一つのセッションマネージャに含まれる複数のsidとその実データを
;;; 同時に利用する事はできないものとする。
;;; -- 複数同時に利用できる事は、悪用と混乱しかもたらさないように思える為。
;;; -- しかし、途中でsidを変更する機能(セッション内のデータは同一)は、
;;; あってもいいかも知れない。
;;; --- とは言え、頻繁に使う機能ではないので、今は実装しない事にする。
(define-module tir04.session
(use gauche.parameter)
(use rfc.sha1)
(use util.digest)
(use math.mt-random)
(export
<session>
with-session
create-session!
update-session!
remove-session!
))
(select-module tir04.session)
;; with-session時の引数省略可能用パラメータ
(define session (make-parameter #f))
;; 子クラスは、このクラスを継承する事。
(define-class <session> ()
(
;; sessionの寿命
(expire-second
:accessor expire-second-of
:init-keyword :expire-second
:init-value (* 1 24 60 60)) ; 仮に一日としておく
;; gcの為のカウンタ
(gc-counter
:accessor gc-counter-of
:init-value 0)
;; 一時データを収めるスロット
(now-sid
:accessor now-sid-of
:init-form (make-parameter #f))
(now-status
;; with-session内で、セッションのデータが操作された際に変更されるフラグ。
;; 以下の値を取る。
;; - 'not-modified
;; - 'created
;; - 'updated
;; - 'removed
:accessor now-status-of
:init-form (make-parameter #f))
))
(define-method initialize ((self <session>) initargs)
(next-method)
;; このクラス自体には、初期化が必要な処理は無し。
;; 子クラスは、もし必要なら、別途自分で用意する事。
#t)
;; 子クラスは、以下のmethodを用意しなくてはならない。
(define-method inner:with-session-prehandler ((self <session>) sid)
;; このmethodは、with-session実行前に呼ばれる。
;; 何か処理が必要なら追加してよい。
#f)
(define-method inner:with-session-posthandler ((self <session>) sid)
;; このmethodは、with-session実行後に呼ばれる。
;; 何か処理が必要なら追加してよい。
;; 尚、dynamic-windによって、エラー例外が投げられた際にも呼ばれる。
;; また、sidは、inner:with-session-prehandlerが呼ばれた時と同じとは限らない。
;; (create-session!やremove-session!で生成削除される可能性がある為)
#f)
(define-method inner:gc-session! ((self <session>))
;; このmethodは、with-session実行時に時々実行される。
;; このmethodが呼ばれたら、セッションマネージャが管理しているセッションを
;; 一通りチェックし、タイムアウト状態になっているものがあれば破棄する事。
;; 尚、いちいちチェックしなくても勝手にgcされるような仕組みで
;; セッションを管理している場合は、この手続きは何も行わなくても構わない。
#f)
(define-method inner:get-session ((self <session>) sid fallback)
;; このmethodは、セッションのデータストレージから、sidに対応するデータを
;; 取り出して返す事。
;; 該当するsidが存在しない場合や、取り出されようとしたsidのライフタイムの
;; 有効期限が切れていた場合は、返り値としてfallbackとして渡された値を返す事。
;; このmethodでは、データストレージからデータを取り出す際に
;; ライフタイムの更新をする必要は無い。
;; しかし、ライフタイムの更新を同時に行ってはいけない訳ではない。
(error "not implemented"))
(define-method inner:touch-session! ((self <session>) sid)
;; このmethodは、指定されたsidのライフタイムの更新を行う事。
;; ライフタイムの実装は、ただ単に更新された日時を何らかの方法で
;; 保持するのが最も簡単だと思われる。
;; (有効期限切れかどうかを判定する際には、(expire-second-of self)が使える)
;; このmethodが呼び出された段階でライフタイムが切れていた場合は、
;; まだライフタイムが有効であったものとして、更新を行うのが望ましい。
;; もし、それが無理な場合は、inner:get-session時にもライフタイムの更新を
;; 行うように実装する必要がある。
(error "not implemented"))
(define-method inner:put-session! ((self <session>) sid session-data)
;; このmethodは、指定されたsidとsession-dataをkeyとvalueとして、
;; ライフタイムを更新しつつ、データストレージに記憶する事。
;; 指定されたsidがまだ存在しない場合は、新たなエントリを生成して記憶する事。
(error "not implemented"))
(define-method inner:delete-session! ((self <session>) sid)
;; このmethodは、指定されたsidに対応するエントリを削除する事。
;; 指定されたエントリが存在しない場合は、何も行わなくてよい。
(error "not implemented"))
;;; 子クラスが表に提供すべきmethod群
;;; これらは、inner:*の各methodを呼び出す為、子が用意する必要は無い。
;;; 但し、モジュールがuseされたら、これらのmethodをexportする事。
(define-method with-session ((self <session>) sid proc)
(parameterize ((session self)
((now-sid-of self) sid)
((now-status-of self) 'not-modified))
(dynamic-wind
(lambda ()
(inner:with-session-prehandler self ((now-sid-of self))))
(lambda ()
(let1 session-data (and sid (inner:get-session self sid #f))
(receive result (proc session-data)
(cond
((eq? ((now-status-of self)) 'not-modified)
;; セッションが存在している時のみライフタイムを更新
(when session-data
(inner:touch-session! self sid)))
((eq? ((now-status-of self)) 'created)
#f) ; 今のところ、何かを行う必要性は無さそう
((eq? ((now-status-of self)) 'updated)
#f) ; 今のところ、何かを行う必要性は無さそう
((eq? ((now-status-of self)) 'removed)
#f) ; 今のところ、何かを行う必要性は無さそう
(else
(error "assertion")))
(when (= 0 (mt-random-integer *mt* 2))
(let1 gc-counter (+ (gc-counter-of self) 1)
(if (< 16 gc-counter) ; 大体32回に一回ぐらいgcが呼ばれる
(begin
(inner:gc-session! self)
(set! (gc-counter-of self) 0))
(set! (gc-counter-of self) gc-counter))))
(values result))))
(lambda ()
(inner:with-session-posthandler self ((now-sid-of self)))))))
(define-method create-session! ((self <session>) session-data)
;;(when ((now-sid-of self))
;; (error "session is already exists"))
;; 既セッションの有無はチェックせずに、常に新規のセッションを作るものとする
;; (理由は、セッション削除を行っても、それはセッション内データの削除を
;; 行うだけなので、依然として外部ではsidを保持しており、
;; セッション作成→セッション削除→セッション作成と行った際に、
;; 二回目のセッション作成の部分でsidを既に持っている為に、
;; 引っかかってしまう。)
(let1 sid (make-sid self)
(inner:put-session! self sid session-data)
((now-sid-of self) sid)
((now-status-of self) 'created)
sid))
(define-method create-session! (session-data)
(unless (session)
(error "cannot found session-manager object"))
(create-session! (session) session-data))
(define-method update-session! ((self <session>) session-data)
(unless ((now-sid-of self))
(error "have not sid"))
(if session-data
(begin
(inner:put-session! self ((now-sid-of self)) session-data)
((now-status-of self) 'updated)
#t)
(remove-session! self))) ; #fが保存されようとしたなら削除する
(define-method update-session! (session-data)
(unless (session)
(error "cannot found session-manager object"))
(update-session! (session) session-data))
(define-method remove-session! ((self <session>))
(unless ((now-sid-of self))
(error "have not sid"))
(inner:delete-session! self ((now-sid-of self)))
((now-sid-of self) #f)
((now-status-of self) 'removed)
#t)
(define-method remove-session! ()
(unless (session)
(error "cannot found session-manager object"))
(remove-session! (session)))
;; sid生成用手続き等
(define *mt*
(make <mersenne-twister>
:seed (receive (epoch micro) (sys-gettimeofday)
(receive (q r) (quotient&remainder epoch (+ (sys-getpid) 1))
(+ q r micro)))))
(define-method make-sid ((self <session>))
(let1 new-sid (digest-hexify
(sha1-digest-string
(x->string
(mt-random-real0 *mt*))))
;; 現在のセッションテーブルに既にこのsidが無い事を確認する必要がある
;; ロックしている訳ではないので、race conditionが発生する可能性はあるが、
;; そもそもsha1 digestを取っているので、その可能性は充分低いので、諦める。
;; もし、inner:get-sessionのコストが結構大きいようなら、
;; この確認作業も省略して構わないかも知れない。
;(if (inner:get-session self new-sid #f)
; (make-sid self)
; new-sid)
;; とりあえず省略する事にした
new-sid))
;;; --------
(provide "tir04/session")
| false |
27b575487c6d876ba4bd779bf48a133cbf4a9b0d
|
7f8e3eb6b64a12225cbc704aedb390f8fb9186de
|
/ch2/2_87a.scm
|
9df577160e2451f7cba265825daae742a72faea9
|
[] |
no_license
|
fasl/sicp
|
70e257b6a5fdd44d2dc5783e99d98f0af527fe45
|
c7228b6b284c525a4195358f91e27ebd6a419fa3
|
refs/heads/master
| 2020-12-26T01:12:07.019658 | 2017-02-01T10:13:38 | 2017-02-01T10:13:38 | 17,853,161 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 14,486 |
scm
|
2_87a.scm
|
(define true #t)
(define false #f)
(define nil '())
class PolynomialArithmetic{
public:
PolynomialArithmetic(const string tagIn="polynomial"):tagString(tagIn){
put(makeList("gcd",makeList(this->getTag(),this->getTag())),
makeLeaf(function<List(List,List)>
([this](const List& x,const List& y)
{return(this->tag(this->gcd(x,y)));})));
put(makeList("add",makeList(this->getTag(),this->getTag())),
makeLeaf(function<List(List,List)>
([this](const List& x,const List& y)
{return(drop(this->tag(this->addPolynomial(x,y))));})));
put(makeList("sub",makeList(this->getTag(),this->getTag())),
makeLeaf(function<List(List,List)>
([this](const List& x,const List& y)
{return(drop(this->tag(this->subPolynomial(x,y))));})));
put(makeList("mul",makeList(this->getTag(),this->getTag())),
makeLeaf(function<List(List,List)>
([this](const List& x,const List& y)
{return(drop(this->tag(this->mulPolynomial(x,y))));})));
put(makeList("div",makeList(this->getTag(),this->getTag())),
makeLeaf(function<List(List,List)>
([this](const List& x,const List& y)
{return(drop(this->tag(this->divPolynomial(x,y))));})));
put(makeList("constant?",makeList(this->getTag())),
makeLeaf(function<List(List)>
([this](const List& x)
{return(this->isConstant(x));})));
put(makeList("=zero?",makeList(this->getTag())),
makeLeaf(function<List(List)>
([this](const List& x)
{return(this->isZero(x));})));
put(makeList("negate",makeList(this->getTag())),
makeLeaf(function<List(List)>
([this](const List& x)
{return(this->tag(this->negate(x)));})));
put(makeList("variable",makeList(this->getTag())),
makeLeaf(function<List(List)>
([this](const List& x)
{return(this->variable(x));})));
put(makeList("leadingCoefficient",makeList(this->getTag())),
makeLeaf(function<List(List)>
([this](const List& x)
{return(this->leadingCoefficient(x));})));
put(makeList("polynomialOrder",makeList(this->getTag())),
makeLeaf(function<List(List)>
([this](const List& x)
{return(this->polynomialOrder(x));})));
put(makeList("expressionString",makeList(this->getTag())),
makeLeaf(function<List(List)>
([this](const List& x)
{return(this->expressionString(x));})));
put(makeList("make",this->getTag()),
makeLeaf(function<List(List,List)>
([this](const List& var, const List& terms)
{return(this->tag
(this->makePolynomial(var,terms)));})));
}
virtual ~PolynomialArithmetic(void){};
const List makePolynomial(const List& variable, const List& termList)const
{return(makeList(variable,termList));}
const List variable(const List& polynomial)const
{return(car(polynomial));}
const List termList(const List& polynomial)const
{return(cadr(polynomial));}
//same-variable?
const bool isSameVariable(const List& v1,const List& v2)const
{return(isVariable(v1) && isVariable(v2) && isEq(v1,v2));}
//variable?
const bool isVariable(const List& x)const
{return(isSymbol(x));}
const List gcd(const List& a, const List& b)const{
if(makeLeaf(0)==b){return(a);}
return(gcd(b,a%b));
}
const List addPolynomial
(const List& p1, const List& p2)const
{
if(this->isSameVariable
(this->variable(p1),this->variable(p2))){
return(this->makePolynomial
(this->variable(p1),
this->addTerms(termList(p1),termList(p2))));
}
cerr<<"Polynomials not in same variable -- ADD-POLY "
<<listString(p1)<<listString(p2)<<endl;
exit(1);
return(makeList());
}
const List addTerms(const List& L1,const List& L2)const
{
if(this->isEmptyTermList(L1)){return(L2);}
else if(this->isEmptyTermList(L2)){return(L1);}
const List t1(this->firstTerm(L1));
const List t2(this->firstTerm(L2));
if(this->order(t1)>this->order(t2)){
return(this->adjoinTerm
(t1,this->addTerms(this->restTerms(L1),L2)));
}else if(this->order(t1)<this->order(t2)){
return(this->adjoinTerm
(t2,this->addTerms(L1,this->restTerms(L2))));
}
return(this->adjoinTerm
(this->makeTerm
(this->order(t1),
Generic::add(this->coefficient(t1),
this->coefficient(t2))),
this->addTerms(this->restTerms(L1),
this->restTerms(L2))));
}
const List subPolynomial
(const List&, const List&)const
{return(makeList());}
const List mulPolynomial
(const List& p1, const List& p2)const
{
if(this->isSameVariable
(this->variable(p1),this->variable(p2))){
return(this->makePolynomial
(this->variable(p1),
this->mulTerms(termList(p1),termList(p2))));
}
cerr<<"Polynomials not in same variable -- MUL-POLY "
<<listString(p1)<<listString(p2)<<endl;
exit(1);
return(makeList());
}
const List mulTerms(const List& L1, const List& L2)const
{
if(this->isEmptyTermList(L1))
{return(this->theEmptyTermList());}
return(this->addTerms
(this->mulTermsByAllTerms(this->firstTerm(L1),L2),
this->mulTerms(this->restTerms(L1),L2)));
}
const List mulTermsByAllTerms(const List& t1, const List& L)const
{
if(this->isEmptyTermList(L))
{return(this->theEmptyTermList());}
const List t2(this->firstTerm(L));
return(this->adjoinTerm
(this->makeTerm
(this->order(t1)+this->order(t2),
Generic::mul(this->coefficient(t1),this->coefficient(t2))),
this->mulTermsByAllTerms(t1,this->restTerms(L))));
}
const List divPolynomial
(const List& x, const List& y)const
{return(makeList());}
const List adjoinTerm(const List& term, const List& termList)const
{
if(Generic::isZero(this->coefficient(term)))
{return(termList);}
return(cons(term,termList));
}
const List theEmptyTermList(void)const{return(makeList());}
const List firstTerm(const List& termList)const
{return(car(termList));}
const List restTerms(const List& termList)const
{return(cdr(termList));}
const bool isEmptyTermList(const List& termList)const
{return(isNull(termList));}
const List makeTerm(const List& order,const List& coefficient)const
{return(makeList(order,coefficient));}
const List order(const List& term)const{return(car(term));}
const List coefficient(const List& term)const{return(cadr(term));}
const List isConstant(const List& x)const
{
return(makeLeaf(this->order
(this->firstTerm(this->termList(x)))==makeLeaf(0)));
}
const List isZero(const List& x)const
{
return(makeLeaf
(isNull(termList(x))
||(this->isConstant(x)
&& Generic::isZero(this->leadingCoefficient(x)))));
}
const List negate(const List& x)const
{
return(this->mulPolynomial
(x,
this->makePolynomial
(this->variable(x),makeList(this->makeTerm(makeLeaf(0),Generic::makeNumber(-1))))));
}
const List leadingCoefficient(const List& x)const
{
return(this->coefficient(this->firstTerm(this->termList(x))));
}
const List polynomialOrder(const List& x)const
{
return(this->order(this->firstTerm(this->termList(x))));
}
const List expressionString(const List& x)const
{
string returnString("");
if(this->isZero(x)!=makeLeaf(0)){return(makeLeaf(returnString));}
const string coefString
(Generic::expressionString(this->leadingCoefficient(x)));
if(typeTag(this->leadingCoefficient(x))=="polynomial"
||typeTag(this->leadingCoefficient(x))=="complex"){
if(this->polynomialOrder(x)!=makeLeaf(0)){
returnString+="+("+coefString+")";
}else{
if(coefString.front()=='-'){
returnString+=coefString;
}else{
returnString+="+"+coefString;
}
}
}else if(coefString.front()=='-'){
if(typeTag(this->leadingCoefficient(x))=="rational"){
returnString+="-("
+Generic::expressionString
(Generic::negate(this->leadingCoefficient(x)))
+")";
}else{
if(Generic::isEqu(this->leadingCoefficient(x),Generic::makeNumber(-1))
&& this->polynomialOrder(x)!=makeLeaf(0)){
returnString+="-";
}else{
returnString+=coefString;
}
}
}else{
if(typeTag(this->leadingCoefficient(x))=="rational"){
returnString+="+("+coefString+")";
}else{
if(Generic::isEqu(this->leadingCoefficient(x),Generic::makeNumber(1))
&& this->polynomialOrder(x)!=makeLeaf(0)){
returnString+="+";
}else{
returnString+="+"+coefString;
}
}
}
if(this->polynomialOrder(x)!=makeLeaf(0)){
returnString+=listString(this->variable(x));
if(this->polynomialOrder(x)!=makeLeaf(1)){
returnString+="^"+listString(this->polynomialOrder(x));
}
}
return(makeLeaf
(returnString
+this->expressionString
(this->makePolynomial(this->variable(x),cdr(this->termList(x))))->getItem()));
}
const TagType getTag(void)const{return(this->tagString);}
virtual const List tag(const List& x)const
{return(attachTag(this->getTag(),x));}
private:
const TagType tagString;
};
PolynomialArithmetic* _polynomialPackage(nullptr);
void installPolynomialPackage(void){
_polynomialPackage=new PolynomialArithmetic();
}
void uninstallPolynomialPackage(void){
if(nullptr!=_polynomialPackage) delete _polynomialPackage;
}
//---------abstraction barrier---------
int main(int argc, char** argv)
{
installNumberPackage();
installRationalPackage();
installRealPackage();
installComplexPackage();
installPolynomialPackage();
installCoercion();
using namespace Generic;
const List p1(makePolynomial
("x",makeList
(makeList(2,makeNumber(3)),
makeList(1,makeComplexFromRealImag(2,3)),
makeList(0,makeNumber(7)))));
const List p2(makePolynomial
("x",makeList
(makeList(4,makeNumber(1)),
makeList(2,makeRational(2,3)),
makeList(0,makeComplexFromRealImag(5,3))
)));
cout<<"p1 = "<<expressionString(p1)<<endl;
cout<<"p2 = "<<expressionString(p2)<<endl;
cout<<"(add p1 p2) = "<<expressionString(add(p1,p2))<<endl;
cout<<"(mul p1 p2) = "<<expressionString(mul(p1,p2))<<endl;
const List py1(makePolynomial
("y",makeList
(makeList(1,makeNumber(1)),
makeList(0,makeNumber(1)))));
const List py2(makePolynomial
("y",makeList
(makeList(2,makeNumber(1)),
makeList(0,makeNumber(1)))));
const List py3(makePolynomial
("y",makeList
(makeList(1,makeNumber(1)),
makeList(0,makeNumber(-1)))));
const List pxy1(makePolynomial
("x",makeList
(makeList(2,py1),
makeList(1,py2),
makeList(0,py3))));
cout<<"pxy1 = "<<expressionString(pxy1)<<endl;
const List py4(makePolynomial
("y",makeList
(makeList(1,makeNumber(1)),
makeList(0,makeNumber(-2)))));
const List py5(makePolynomial
("y",makeList
(makeList(3,makeNumber(1)),
makeList(0,makeNumber(7)))));
const List pxy2(makePolynomial
("x",makeList
(makeList(1,py4),
makeList(0,py5))));
cout<<"pxy2 = "<<expressionString(pxy2)<<endl;
cout<<"(mul pxy1 pxy2) = "<<expressionString(mul(pxy1,pxy2))<<endl;
cout<<endl<<"Excersize 2.87:"<<endl;
const List p3(makePolynomial("x",makeList(makeList(0,makeNumber(0)))));
cout<<"p3 = "<<expressionString(drop(p3))<<endl;
cout<<"(=zero? p3) = "<<isZero(p3)<<endl;
cout<<"(mul p1 p3) = "<<expressionString(mul(p1,p3))<<endl;
cout<<endl<<"Excersize 2.88:"<<endl;
const List p4(Generic::negate(p2));
cout<<"p4 = (negate p2) = "<<expressionString(p4)<<endl;
cout<<"(add p2 p4) = "<<expressionString(add(p2,p4))<<endl;
cout<<"(sub p1 p2) = "<<expressionString(sub(p1,p2))<<endl;
uninstallNumberPackage();
uninstallRationalPackage();
uninstallRealPackage();
uninstallComplexPackage();
uninstallPolynomialPackage();
return(0);
}
| false |
c7c1545a4624802c2daa6407ce446842872f20a1
|
b9eb119317d72a6742dce6db5be8c1f78c7275ad
|
/scsh/dir-fold/packages.scm
|
826c0467ff22d08ce4b955b2ec1e18c81bdfe742
|
[] |
no_license
|
offby1/doodles
|
be811b1004b262f69365d645a9ae837d87d7f707
|
316c4a0dedb8e4fde2da351a8de98a5725367901
|
refs/heads/master
| 2023-02-21T05:07:52.295903 | 2022-05-15T18:08:58 | 2022-05-15T18:08:58 | 512,608 | 2 | 1 | null | 2023-02-14T22:19:40 | 2010-02-11T04:24:52 |
Scheme
|
UTF-8
|
Scheme
| false | false | 234 |
scm
|
packages.scm
|
;; -*- mode: scheme48; scheme48-package: config -*-
(define-structure dir-fold (export directory-fold safe-directory-fold directory-tree-fold pruning-tree-fold)
(open scheme-with-scsh srfi-1 handle conditions)
(files dir-fold))
| false |
3fc4c870af47ac6387549bfacd2581441734f681
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/security/cryptography/password-derive-bytes.sls
|
a2592a60b68121a148d2946bda67b509b104de4a
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,851 |
sls
|
password-derive-bytes.sls
|
(library (system security cryptography password-derive-bytes)
(export new
is?
password-derive-bytes?
get-bytes
crypt-derive-key
reset
hash-name-get
hash-name-set!
hash-name-update!
iteration-count-get
iteration-count-set!
iteration-count-update!
salt-get
salt-set!
salt-update!)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Security.Cryptography.PasswordDeriveBytes
a
...)))))
(define (is? a)
(clr-is System.Security.Cryptography.PasswordDeriveBytes a))
(define (password-derive-bytes? a)
(clr-is System.Security.Cryptography.PasswordDeriveBytes a))
(define-method-port
get-bytes
System.Security.Cryptography.PasswordDeriveBytes
GetBytes
(System.Byte[] System.Int32))
(define-method-port
crypt-derive-key
System.Security.Cryptography.PasswordDeriveBytes
CryptDeriveKey
(System.Byte[]
System.String
System.String
System.Int32
System.Byte[]))
(define-method-port
reset
System.Security.Cryptography.PasswordDeriveBytes
Reset
(System.Void))
(define-field-port
hash-name-get
hash-name-set!
hash-name-update!
(property:)
System.Security.Cryptography.PasswordDeriveBytes
HashName
System.String)
(define-field-port
iteration-count-get
iteration-count-set!
iteration-count-update!
(property:)
System.Security.Cryptography.PasswordDeriveBytes
IterationCount
System.Int32)
(define-field-port
salt-get
salt-set!
salt-update!
(property:)
System.Security.Cryptography.PasswordDeriveBytes
Salt
System.Byte[]))
| true |
79e0ef4a8e2c15cba48c6aef6688addf910f540c
|
84d08da008fb9828d754375ee94e0b97e859c301
|
/test/mocks/gram/view.scm
|
9d6bcba7685650b371dfee1529501bcba53ff098
|
[
"BSD-3-Clause"
] |
permissive
|
emallson/gram
|
4263c9edf1edda40eb5904591b98736749741fe4
|
1023a0ab2998fb27e7f71aeada11acbae91d4a23
|
refs/heads/master
| 2021-01-21T04:40:50.085623 | 2020-12-19T17:40:33 | 2020-12-19T17:40:33 | 50,430,299 | 21 | 2 | null | 2016-04-07T17:41:06 | 2016-01-26T13:29:06 |
C
|
UTF-8
|
Scheme
| false | false | 375 |
scm
|
view.scm
|
(define-module (gram view)
#:use-module (srfi srfi-9 gnu)
#:use-module (gram support utils)
#:export (view? set-output set-geometry))
(define-immutable-record-type view
(make-view)
_view?)
(define (view? v)
(if (equal? v 'test-view)
#t
(error (format "view? called with input ~a" v))))
(define-dead-mock set-output)
(define-dead-mock set-geometry)
| false |
3ab197bf683eb501d91c4607ba9a35ffd885cf11
|
6c6cf6e4b77640825c2457e54052a56d5de6f4d2
|
/ch2/2_61-test.scm
|
3be791716638a1fc16df61c53ad6a56b5f3a5027
|
[] |
no_license
|
leonacwa/sicp
|
a469c7bc96e0c47e4658dccd7c5309350090a746
|
d880b482d8027b7111678eff8d1c848e156d5374
|
refs/heads/master
| 2018-12-28T07:20:30.118868 | 2015-02-07T16:40:10 | 2015-02-07T16:40:10 | 11,738,761 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 374 |
scm
|
2_61-test.scm
|
;ex 2.61 adjoin-set test
(load "s2_3_3-set2.scm")
(load "2_61-adjoin-set.scm")
(define set1 (list 1 2 3 4 5))
(define set2 (list 3 4 5 6 7))
(display (element-of-set? 2 set1))
(newline)
(display (element-of-set? 0 set1))
(newline)
(print-set (adjoin-set 0 set1))
(print-set (adjoin-set 0 set2))
(print-set (adjoin-set 10 set2))
(print-set (intersetion-set set1 set2))
| false |
3e1df7a42d31c79d60284f331d012ae954f48265
|
2163cd08beac073044187423727f84510a1dbc34
|
/chapter-2/sicp_ch2_e2-25.scm
|
58ae6fba032aee8f0739960231f89bff87bac50a
|
[] |
no_license
|
radiganm/sicp
|
b40995ad4d681e2950698295df1bbe3a75565528
|
32a7dcdf5678bb54d07ee3ee8a824842907489f0
|
refs/heads/master
| 2021-01-19T10:48:52.579235 | 2016-12-12T10:47:18 | 2016-12-12T10:47:18 | 63,052,284 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 537 |
scm
|
sicp_ch2_e2-25.scm
|
#!/usr/bin/csi -s
;; sicp_ch2_e2-25.scm
;; Mac Radigan
(load "../library/util.scm")
(import util)
;;; Exercise 2.25. Give combinations of cars and cdrs that will pick 7 from
;;; each of the following lists:
;;;
;;; (1 3 (5 7) 9)
;;; ((7))
;;; (1 (2 (3 (4 (5 (6 7))))))
(define L1 '(1 3 (5 7) 9) )
(define L2 '((7)) )
(define L3 '(1 (2 (3 (4 (5 (6 7)))))) )
(bar)
(prnvar "L1" (car (cdaddr L1)))
(prnvar "L2" (caar L2))
(prnvar "L3" (car (cdr (cadr (cadr (cadr (cadr (cadr L3))))))))
(br)
(bar)
;; *EOF*
| false |
95a65d814df35b2ed3857ee216353e1dc4a8e499
|
6eaa87ed57fab28bb4b3b95a1aa721978947f3ec
|
/lib/assert.scm
|
100f3d8958c164c1967fd7f0a307b03990ad0e23
|
[
"MIT"
] |
permissive
|
seven1m/scheme-vm
|
d8b28d79faf400e260c445c2e72aaf2a78182c92
|
00cdee125690429c16b1e5b71b180a6899ac6a58
|
refs/heads/master
| 2021-01-21T16:53:03.742073 | 2018-04-17T01:06:45 | 2018-04-17T01:06:45 | 27,324,674 | 9 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,138 |
scm
|
assert.scm
|
(define-library (assert)
(import (only (scheme base) begin define-syntax = eq? eqv? equal? if newline not quote write-string))
(export assert)
(begin
(define-syntax assert
(syntax-rules (eq? eqv? equal?)
((assert (= expected actual))
(assert (= expected actual) expected actual))
((assert (eq? expected actual))
(assert (eq? expected actual) expected actual))
((assert (eqv? expected actual))
(assert (eqv? expected actual) expected actual))
((assert (equal? expected actual))
(assert (equal? expected actual) expected actual))
((assert expr)
(assert expr (quote (not #f)) expr))
((assert expr expected actual)
(if (not expr)
(begin
(write-string "(assert ")
(write-string (quote expr))
(write-string ") failed:")
(newline)
(write-string " expected: ")
(write-string expected)
(newline)
(write-string " actual: ")
(write-string actual)
(newline))))))))
| true |
af01898e0c1bf41c60cdb33b3223b7495ae332a1
|
d63c4c79d0bf83ae646d0ac023ee0528a0f4a879
|
/cs133/assn3/a3q5.ss
|
ef173bc17a6cead3b6a6de61607fe5373834e82b
|
[] |
no_license
|
stratigoster/UW
|
4dc31f08f7f1c9a958301105dcad481c39c5361f
|
7a4bff4f1476607c43278c488f70d01077b1566b
|
refs/heads/master
| 2021-07-07T04:52:01.543221 | 2011-08-15T05:08:48 | 2011-08-15T05:08:48 | 10,858,995 | 1 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,499 |
ss
|
a3q5.ss
|
;; contract- remove-duplicates: lon -> lon
;; purpose- to consume a list of numbers (lon) and produce the list with all but the first occurrence of every number removed
;; examples-
;; (remove-duplicates (cons 1 (cons 3 (cons 1 (cons 4 empty))))) => (cons 1 (cons 3 (cons 4 empty)))
;; (remove-duplicates (cons 1 (cons 2 (cons 3 empty)))) => (cons 1 (cons 2 (cons 3 empty)))
(define (remove-duplicates numlist)
(reverse (remove (reverse numlist)))) ;; sends in a reversed list, so it has to reverse the output to make it the right order
;; contract- contains: num lon -> boolean
;; purpose- to consume a number and a list of numbers (lon) and outputs true iff the number is on the list
;; examples-
;; (contains 5 (cons 1 (cons 2 (cons 5 (cons 4 empty))))) => true
;; (contains 10 (cons 1 (cons 2 (cons 5 (cons 4 empty))))) => false
(define (contains? num numlist)
(cond
[(empty? numlist) false]
[else
(cond
[(= num (first numlist)) true]
[else (contains? num (rest numlist))])]))
;; tests
(equal? (contains? 5 (cons 1 (cons 2 (cons 5 (cons 4 empty))))) true)
(equal? (contains? 5 (cons 1 (cons 2 (cons 3 (cons 4 empty))))) false)
(equal? (contains? 5 (cons 5 (cons 2 (cons 5 (cons 4 empty))))) true)
;; contract- remove: lon -> lon
;; purpose- to perform the actual removal of the duplicated elements
;; it has the reversed list passed in, then checks each element to see if it occurs again in the list. If it does, then it skips that element otherwise the element is added to the new list
;; examples:
;; (remove (cons 4 (cons 2 (cons 4 empty)))) => (cons 2 (cons 4 empty))
;; (remove (cons 4 (cons 1 (cons 2 (cons 1 (cons 4 empty)))))) => (cons 2 (cons 1 (cons 4 empty)))
(define (remove numlist)
(cond
[(empty? numlist) empty]
[(contains? (first numlist) (rest numlist)) (remove (rest numlist))]
[else (cons (first numlist) (remove (rest numlist)))]))
;; testing remove
(equal? (remove (cons 4 (cons 2 (cons 4 empty)))) (cons 2 (cons 4 empty)))
(equal? (remove (cons 4 (cons 1 (cons 2 (cons 1 (cons 4 empty)))))) (cons 2 (cons 1 (cons 4 empty))))
;; tests
(equal? (remove-duplicates (cons 1 (cons 2 (cons 3 empty)))) (cons 1 (cons 2 (cons 3 empty))))
(equal? (remove-duplicates (cons 1 (cons 4 (cons 2 (cons 1 (cons 5 (cons 4 empty)))))))
(cons 1 (cons 4 (cons 2 (cons 5 empty)))))
(equal? (remove-duplicates (cons 1 (cons 3 (cons 1 (cons 4 empty))))) (cons 1 (cons 3 (cons 4 empty))))
| false |
186183e2879ee618d3b0c20ff066f73ecd90fc0a
|
958488bc7f3c2044206e0358e56d7690b6ae696c
|
/scheme/digital/simple/bus-test.scm
|
7932b0959c91bb7bbda6be75088548d51b8309ee
|
[] |
no_license
|
possientis/Prog
|
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
|
d4b3debc37610a88e0dac3ac5914903604fd1d1f
|
refs/heads/master
| 2023-08-17T09:15:17.723600 | 2023-08-11T12:32:59 | 2023-08-11T12:32:59 | 40,361,602 | 3 | 0 | null | 2023-03-27T05:53:58 | 2015-08-07T13:24:19 |
Coq
|
UTF-8
|
Scheme
| false | false | 3,108 |
scm
|
bus-test.scm
|
(load "bus.scm")
(define (bus-test)
(define a (bus 12))
(define b (bus 8))
(define x (bus 16))
(define y (bus 16))
(define s (bus 16))
(define cin (wire))
(define cout (wire))
;; start
(display "bus: starting unit test\n")
(if (not (= 12 (a 'size))) (display "bus: unit test 1 failing\n"))
(if (not (= 8 (b 'size))) (display "bus: unit test 2 failing\n"))
;; testing set-signal! and get-signal
;; testing bus a
(let ((N (expt 2 (a 'size)))) ;; highest unsigned integer on bus + 1
(let loop ((i 0))
(if (< i N)
(begin
((a 'set-signal!) i)
(if (not (= i (a 'get-signal)))
(begin
(display "bus: unit test 3 failing for integer ")
(display i)
(newline)))
(loop (+ i 1))))))
;; testing bus b
(let ((N (expt 2 (b 'size)))) ;; highest unsigned integer on bus + 1
(let loop ((i 0))
(if (< i N)
(begin
((b 'set-signal!) i)
(if (not (= i (b 'get-signal)))
(begin
(display "bus: unit test 4 failing for integer ")
(display i)
(newline)))
(loop (+ i 1))))))
;; testing get-wire
((a 'set-signal!) (- (expt 2 (a 'size)) 1)) ; all bits set to 1
(let loop ((i 0))
(if (< i (a 'size))
(begin
(let ((signal (((a 'get-wire) i) 'get-signal))) ;ith bit = signal
(if (not (eq? #t signal))
(begin
(display "bus: unit test 5 failing for bit ")
(display i)
(newline))))
(loop (+ i 1)))))
((a 'set-signal!) 0) ; all bits sets to 0
(let loop ((i 0))
(if (< i (a 'size))
(begin
(let ((signal (((a 'get-wire) i) 'get-signal))) ;ith bit = signal
(if (not (eq? #f signal))
(begin
(display "bus: unit test 6 failing for bit ")
(display i)
(newline))))
(loop (+ i 1)))))
;; testing ripple adder
(ripple-adder x y cin s cout)
(let ((N 64))
(let loopX ((i 0))
(if (< i N)
(begin
(let loopY ((j 0))
(if (< j N)
(begin
((cin 'set-signal!) #f) ; ensures input carry is off
((x 'set-signal!) i)
((y 'set-signal!) j)
(schedule 'propagate!) ; computes i + j -> bus s
(if (not (= (+ i j) (s 'get-signal)))
(display "bus: unit test 7 failing\n"))
(if (not (eq? #f (cout 'get-signal)))
(display "bus: unit test 8 failing\n"))
((cin 'set-signal!) #t) ; ensures input carry is on
(schedule 'propagate!) ; computes i + j + 1 -> bus s
(if (not (= (+ i j 1) (s 'get-signal)))
(display "bus: unit test 9 failing\n"))
(if (not (eq? #f (cout 'get-signal)))
(display "bus: unit test 10 failing\n"))
(loopY (+ j 1)))))
(loopX (+ i 1))))))
;; end
(display "bus: unit test complete\n"))
(bus-test)
(exit 0)
| false |
4239d6b332e6616accdeaedaf65ff33015dfe7d7
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/sitelib/text/yaml/builder.scm
|
176dbb26ac833646b8c5d510d48f0b2afd58c65c
|
[
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"BSD-2-Clause"
] |
permissive
|
ktakashi/sagittarius-scheme
|
0a6d23a9004e8775792ebe27a395366457daba81
|
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
|
refs/heads/master
| 2023-09-01T23:45:52.702741 | 2023-08-31T10:36:08 | 2023-08-31T10:36:08 | 41,153,733 | 48 | 7 |
NOASSERTION
| 2022-07-13T18:04:42 | 2015-08-21T12:07:54 |
Scheme
|
UTF-8
|
Scheme
| false | false | 14,245 |
scm
|
builder.scm
|
;;; -*- mode:scheme; coding:utf-8 -*-
;;;
;;; text/yaml/builder.scm - YAML - SEXP builder
;;;
;;; Copyright (c) 2018 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
#!nounbound
(library (text yaml builder)
(export yaml->sexp
+default-yaml-builders+
+json-compat-yaml-builders+
+scheme-object-yaml-builders+
;; for testing
date->yaml-canonical-date)
(import (rnrs)
(text yaml conditions)
(text yaml nodes)
(text yaml tags)
(text yaml tokens)
(rfc base64)
(srfi :1 lists)
(srfi :13 strings)
(srfi :14 char-sets)
(srfi :19 time)
(srfi :113 sets)
(srfi :114 comparators)
(srfi :115 regexp))
(define-condition-type &yaml-builder &yaml
make-yaml-builder-error yaml-builder-error?
(when yaml-builder-error-when)
(node yaml-builder-error-node))
(define (yaml-builder-error node when message . irr)
(raise (apply condition
(filter-map values
(list
(make-yaml-builder-error when node)
(and (yaml-node-start-mark node)
(yaml-scanner-mark->condition
(yaml-node-start-mark node)))
(make-who-condition 'yaml->sexp)
(make-message-condition message)
(and (not (null? irr))
(make-irritants-condition irr)))))))
(define yaml->sexp
(case-lambda
((node) (yaml->sexp node +default-yaml-builders+))
((node builders)
(cond ((yaml-document? node)
(yaml->sexp (yaml-document-root-node node) builders))
((yaml-node? node)
(let ((objs (make-eq-hashtable)))
(build-sexp node builders objs)))
(else (assertion-violation 'yaml->sexp
"YAML node or document required" node))))))
(define (build-sexp node builders constructed-objects)
(define tag (yaml-node-tag node))
(define (find-builder builder)
(let ((pred (car builder))
(expected-tag (cadr builder)))
(and (pred node) (string=? expected-tag tag))))
(let ((builder (find find-builder builders)))
(unless builder
(yaml-builder-error node "While searching for a builder"
"The node/tag is not supported with the given set of builders"
(yaml-node-tag node)))
((cddr builder) node
(lambda (next-node)
(when (eq? next-node node)
(error 'yaml->sexp "[Internal] Recursive building of the node" node))
(cond ((hashtable-ref constructed-objects next-node #f))
(else
(let ((r (build-sexp next-node builders constructed-objects)))
(hashtable-set! constructed-objects next-node r)
r)))))))
;;; Builders
(define (->binary v) (base64-decode-string v :transcoder #f))
(define (->bool v)
(or (and (memv (char-downcase (string-ref v 0)) '(#\y #\t)) #t)
(string=? (string-downcase v) "on")))
(define (parse-sexagesimal n)
(let ((tokens (reverse
(map string->number (string-tokenize n char-set:digit)))))
(do ((tokens tokens (cdr tokens))
(coef 0 (+ coef 1))
(r 0 (+ (* (car tokens) (expt 60 coef)) r)))
((null? tokens) r))))
(define (strip-sign v)
(case (string-ref v 0)
((#\-) (values #t (substring v 1 (string-length v))))
((#\+) (values #f (substring v 1 (string-length v))))
(else (values #f v))))
(define (->int v)
(define (handle-number n radix) (string->number (string-delete #\_ n) radix))
(define (handle-binary n) (handle-number n 2))
(define (handle-hex n) (handle-number n 16))
(define (handle-octet n) (handle-number n 8))
(define (handle-decimal n) (handle-number n 10))
(define (handle-sexagesimal n) (parse-sexagesimal (string-delete #\_ n)))
(let-values (((neg n) (strip-sign v)))
(let ((i (case (string-ref n 0)
((#\0)
(if (= (string-length n) 1)
0
(case (string-ref n 1)
((#\b) (handle-binary (substring n 2 (string-length n))))
((#\x) (handle-hex (substring n 2 (string-length n))))
(else
(if (> (string-length n) 1)
(handle-octet (substring n 1 (string-length n)))
(handle-decimal n))))))
(else
(if (string-index n #\:)
(handle-sexagesimal n)
(handle-decimal n))))))
(if neg
(- i)
i))))
(define (->float v)
(let-values (((neg n) (strip-sign v)))
(let* ((ln (string-downcase (string-delete #\_ n)))
(v (cond ((member ln '(".inf" ".Inf" ".INF")) +inf.0)
((member ln '(".nan" ".NaN" ".NAN")) +nan.0)
((string-index ln #\:)
(let* ((i (string-index ln #\.))
(int (substring ln 0 i))
(frac (substring ln i (string-length ln))))
(+ (parse-sexagesimal int) (string->number frac))))
(else (string->number ln)))))
(inexact (if neg (- v) v)))))
(define +time-separators-set+ (char-set #\space #\tab #\T #\t))
(define (->date v)
(define len (string-length v))
(define (parse-ymd ymd)
(values (string->number (substring ymd 0 4))
(string->number (substring ymd 5 7))
(string->number (substring ymd 8 10))))
(define (fraction->nanosecond v)
(* (case (string-length v)
((0) 0) ;; error?
((1) (* (string->number v) 100))
((2) (* (string->number v) 10))
((3) (string->number v))
(else ;; we truncate to millis
(string->number (substring v 0 3))))
1000000))
(define (parse-fraction&offset f&o?)
(cond ((zero? (string-length f&o?)) (values 0 0))
((string-index f&o? #\Z) =>
(lambda (i) (values (fraction->nanosecond (substring f&o? 0 i)) 0)))
((string-index f&o? (char-set #\- #\+)) =>
(lambda (i)
(let ((f (fraction->nanosecond (substring f&o? 0 i)))
(neg (eqv? (string-ref f&o? i) #\-))
(h&m (substring f&o? (+ i 1) (string-length f&o?))))
(let-values (((h m)
(cond ((string-index h&m #\:) =>
(lambda (i)
(values (substring h&m 0 i)
(substring h&m (+ i 1)
(string-length h&m)))))
(else (values h&m #f)))))
(let ((n (+ (* (string->number h) 3600)
(if m (string->number m) 0))))
(values f (if neg (- n ) n)))))))))
(let-values (((ymd rest)
(cond ((string-index v +time-separators-set+) =>
(lambda (i)
(values (substring v 0 i) (substring v i len))))
(else (values v "")))))
(if (= len (string-length ymd))
(let-values (((y m d) (parse-ymd ymd)))
(make-date 0 0 0 0 d m y 0))
(let-values (((hms rest)
(let ((hms-i (string-skip rest +time-separators-set+)))
(cond ((string-index rest #\.) =>
(lambda (i)
(values (substring rest hms-i i)
(substring rest (+ i 1)
(string-length rest)))))
((string-index rest (char-set #\Z #\+ #\-)) =>
(lambda (i)
(values (substring rest hms-i i)
(substring rest i
(string-length rest)))))
(else (values (substring rest hms-i
(string-length rest))
""))))))
(let-values (((fraction offset)
(parse-fraction&offset
(string-delete char-set:whitespace rest)))
((h m s) (apply values
(map string->number
(string-tokenize hms
char-set:digit))))
((y M d) (parse-ymd ymd)))
(make-date fraction s m h d M y offset))))))
;; TODO move it somewhere
(define (date->yaml-canonical-date d)
(define (->iso-zone offset)
(define o (abs offset))
(let* ((h (div o 3600))
(m (- o (* h 3600))))
(string-append (if (negative? offset) "-" "+")
(number->string h)
":"
(number->string m))))
(let ((iso-time (date->string d "~5"))
(milli (div (date-nanosecond d) 1000000))
(offset (date-zone-offset d)))
(string-append iso-time
(if (zero? milli)
""
(string-append "." (number->string milli)))
(if (zero? offset)
"Z"
(->iso-zone offset)))))
(define (->date-string v) (date->yaml-canonical-date (->date v)))
;; (node builder) -> list
(define (->sequence seq builder) (map builder (yaml-node-value seq)))
;; (node builder) -> vector
(define (generic-mapping mapping key-builder value-builder)
(define (flatten-mapping value)
(define (handle-merge k v acc)
(cond ((yaml-mapping-node? v) (append (flatten-mapping v) acc))
((yaml-sequence-node? v)
(append (append-map (lambda (v)
(unless (yaml-mapping-node? v)
(yaml-builder-error v
"While building a mapping"
"Expected a mapping for merging"))
(flatten-mapping v))
(yaml-node-value v))
acc))
(else
(yaml-builder-error v
"While building a mapping"
"Expected a mapping or list of mappings for merging"))))
(fold-right (lambda (k&v acc)
(let ((k (car k&v))
(v (cdr k&v)))
(if (string=? (yaml-node-tag k) +yaml-tag:merge+)
(handle-merge k v acc)
(cons (cons k v) acc))))
'() (yaml-node-value value)))
(let ((value (flatten-mapping mapping)))
(delete-duplicates!
(map (lambda (k&v)
(cons (key-builder (car k&v)) (value-builder (cdr k&v)))) value)
(lambda (x y) (equal? (car x) (car y))))))
(define (->mapping mapping builder)
(list->vector (generic-mapping mapping builder builder)))
(define (->set mapping builder)
(list->vector (generic-mapping mapping builder (lambda (_) 'null))))
(define (->pairs pairs builder)
(map (lambda (m)
(let ((v (car (yaml-node-value m))))
(list (builder (car v)) (builder (cdr v)))))
(yaml-node-value pairs)))
(define (list-of-node? v)
(and (list? v) (for-all yaml-node? v)))
(define (list-of-pair? v)
(and (list? v) (for-all (lambda (k&v)
(and (pair? k&v)
(yaml-node? (car k&v))
(yaml-node? (cdr k&v)))) v)))
(define (list-of-single-valued-mapping? v)
(and (list? v) (for-all (lambda (m)
(and (mapping-node? m)
(= (length (yaml-node-value m)) 1))) v)))
(define (entry pred tag builder) (cons* pred tag builder))
(define (single-valued p) (lambda (node builders) (p (yaml-node-value node))))
(define (single-entry pred tag p) (cons* pred tag (single-valued p)))
(define (regexp-pred pred sre)
(define re (regexp sre))
(lambda (node)
(and (pred node)
(regexp-matches re (yaml-node-value node)))))
(define (value-pred pred value-pred)
(lambda (node)
(and (pred node)
(value-pred (yaml-node-value node)))))
(define (add-yaml-builder-entry base . entry*) (append base entry*))
(define (replace-yaml-builder-entry base . entry*)
(let* ((tags (map cadr entry*))
(l (remp (lambda (e) (member (cadr e) tags string=?)) base)))
(append l entry*)))
(define sequence-node? (value-pred yaml-sequence-node? list-of-node?))
(define mapping-node? (value-pred yaml-mapping-node? list-of-pair?))
(define pairs-node?
(value-pred yaml-sequence-node? list-of-single-valued-mapping?))
(define omap-node? pairs-node?)
;; explicit tag should allow float without fraction
(define float-value
`(or ,+yaml-regexp:float+
;; integer 10 base
(: (? ("-+")) (or #\0 (: (/ "19") (* ("_9876543210")))))))
(define +json-compat-yaml-builders+
`(
,(single-entry yaml-scalar-node? +yaml-tag:null+ (lambda (_) 'null))
,(single-entry yaml-scalar-node? +yaml-tag:str+ values)
,(single-entry yaml-scalar-node? +yaml-tag:value+ values)
,(single-entry yaml-scalar-node? +yaml-tag:binary+ ->binary)
,(single-entry (regexp-pred yaml-scalar-node? +yaml-regexp:bool+)
+yaml-tag:bool+ ->bool)
,(single-entry (regexp-pred yaml-scalar-node? +yaml-regexp:int+)
+yaml-tag:int+ ->int)
,(single-entry (regexp-pred yaml-scalar-node? float-value)
+yaml-tag:float+ ->float)
,(single-entry (regexp-pred yaml-scalar-node? +yaml-regexp:timestamp+)
+yaml-tag:timestamp+ ->date-string)
,(entry sequence-node? +yaml-tag:seq+ ->sequence)
,(entry mapping-node? +yaml-tag:map+ ->mapping)
,(entry pairs-node? +yaml-tag:pairs+ ->pairs)
,(entry omap-node? +yaml-tag:omap+ ->pairs) ;; lazy
,(entry mapping-node? +yaml-tag:set+ ->set)
))
(define +default-yaml-builders+ +json-compat-yaml-builders+)
;;; convert to scheme object
(define (->hashtable mapping builder)
(let ((ht (make-hashtable equal-hash equal?)))
(for-each (lambda (kv) (hashtable-set! ht (car kv) (cdr kv)))
(generic-mapping mapping builder builder))
ht))
(define (->vector seq builder) (list->vector (->sequence seq builder)))
(define (->pair-vector pairs builder)
(vector-map (lambda (v) (cons (vector-ref v 0) (vector-ref v 1)))
(->pairs pairs builder)))
(define (->srfi-set mapping builder)
(apply set default-comparator
(map car (generic-mapping mapping builder values))))
(define +scheme-object-yaml-builders+
(replace-yaml-builder-entry +default-yaml-builders+
(single-entry (regexp-pred yaml-scalar-node? +yaml-regexp:timestamp+)
+yaml-tag:timestamp+ ->date)
(entry mapping-node? +yaml-tag:map+ ->hashtable)
(entry sequence-node? +yaml-tag:seq+ ->vector)
(entry sequence-node? +yaml-tag:pairs+ ->pair-vector)
(entry mapping-node? +yaml-tag:set+ ->srfi-set)
;; TODO omap, use SRFI-146 mapping?
))
)
| false |
c24ebe2c1cec023de674abacd268e5eed6962d04
|
323d2a98cec91f5bd5f805f745a9085e027cc10d
|
/Resources/web/app/confirm-delete.ss
|
b5b7aabac3d2c4adcca1c4df082b9183bf8b839c
|
[
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
becls/convert-and-search
|
11a559580c9b1a2e48a5e6b583b9a3e1cb32420b
|
e5731689e354175551a388ba744a494f4d0f3ab0
|
refs/heads/dev
| 2023-02-09T04:55:24.531041 | 2023-02-03T18:29:55 | 2023-02-03T18:29:55 | 144,314,963 | 1 | 0 |
MIT
| 2023-02-03T18:29:57 | 2018-08-10T17:31:01 |
Scheme
|
UTF-8
|
Scheme
| false | false | 4,218 |
ss
|
confirm-delete.ss
|
;;; Copyright 2018 Beckman Coulter, Inc.
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
(http:include "components.ss")
(import (helpers))
;; HTML responses
(define-syntax respond
(syntax-rules ()
[(_ c1 c2 ...)
(hosted-page "Confirm delete"
(list (css-include "css/confirm-delete.css"))
c1 c2 ...)]))
(define (instruct message value link type)
(respond message `(p ,value)
`(table (tr (td (@ (class "nav")) ,link)
(td (@ (class "nav")) (form
(input (@ (id "click") (name "click") (class "hidden")))
(input (@ (id "val") (name "val") (class "hidden") (value ,value)))
(input (@ (id "type") (name "type") (class "hidden") (value ,type)))
(p (button (@ (type "submit")) "Delete"))))))))
(define (delete-and-show-confirmation value type)
(define (return-to-saved)
(match type
["database" (redirect "/app/saved?type=database&sql=&limit=100&offset=0&flag=Delete+Successful")]
["dataAll" (redirect "/app/saved?type=database&sql=&limit=100&offset=0&flag=Delete+Successful")]
["search" (redirect "/app/saved?type=search&sql=&limit=100&offset=0&flag=Delete+Successful")]
["searchAll" (redirect "/app/saved?type=search&sql=&limit=100&offset=0&flag=Delete+Successful")]))
(define (do-delete)
(cond [(string=? "dataAll" type)
(transaction 'log-db (execute "delete from database"))]
[(string=? "searchAll" type)
(transaction 'log-db (execute "delete from search"))]
[else (transaction 'log-db (execute
(format "delete from ~a where ~a = ~a" type
(match type ["database" "file_path"] ["search" "sqlite"])
(quote-sqlite-identifier value))))]))
(match (catch (do-delete))
[#(EXIT ,reason) (respond `(p ,reason))]
[,val (return-to-saved)]))
(define (dispatch)
(let* ([delete-clicked (string-param "click" params)]
[value (string-param "val" params)]
[value (or value "")]
[type (get-param "type")]
[link
(match type
["database" (link "saved?type=database&sql=&limit=100&offset=0" "Cancel")]
["dataAll" (link "saved?type=database&sql=&limit=100&offset=0" "Cancel")]
["search" (link "saved?type=search&sql=&limit=100&offset=0" "Cancel")]
["searchAll" (link "saved?type=search&sql=&limit=100&offset=0" "Cancel")])]
[message
(match type
["database" `(p "Are you sure you wish to delete this database?" (br) "The database will not be removed from memory, just from this application.")]
["dataAll" `(p "Are you sure you would like to remove ALL databases?")]
["search" `(p "Are you sure you want to remove this search?")]
["searchAll" `(p "Are you sure you would like to remove ALL saved searches?")])])
(if delete-clicked
(delete-and-show-confirmation value type)
(instruct message value link type))))
(dispatch)
| true |
8439af8ababece8f9f141ed1d6c473afb61d2428
|
0a345b89eae9a12e18e8d30f24d592a724284a59
|
/libmdal/schemta-tests/m6809.tests.scm
|
93d9ed3ff97e1e81c3760bbc425d24792fddf748
|
[
"MIT"
] |
permissive
|
DeMOSic/bintracker
|
7b26ecb3b8ad315727bb65f1051206b2dcac7123
|
bed6356b7d177d969ea3873527a1698a00305acf
|
refs/heads/master
| 2023-03-26T19:11:49.396339 | 2021-03-29T08:51:12 | 2021-03-29T08:51:12 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 9,019 |
scm
|
m6809.tests.scm
|
(import scheme (chicken base) test schemta)
(define (run-src src)
(map char->integer (assemble 'm6809 src)))
(test-group
"Addressing Modes"
(test "immediate" '(#x89 #xff) (run-src " adca #$ff"))
(test "direct" '(#x99 #xff) (run-src " adca <$ffff"))
(test "extended" '(#xb9 #xff #xfe) (run-src " adca $fffe"))
(test "extended-indirect" '(#xa9 #x9f #xff #xfe) (run-src " adca [$fffe]"))
(test "indexed-autoinc2" '(#xa9 #xa1) (run-src " adca ,y++"))
(test "indexed-autoinc1" '(#xa9 #xa0) (run-src " adca ,y+"))
(test "indexed-autodec2" '(#xa9 #xa3) (run-src " adca ,--y"))
(test "indexed-autodec1" '(#xa9 #xa2) (run-src " adca ,-y"))
(test "indexed-autoinc2-indirect" '(#xa9 #xb1) (run-src " adca [,y++]"))
(test "indexed-autodec2-indirect" '(#xa9 #xb3) (run-src " adca [,--y]"))
(test "indexed-constant-null-offset-from-r" '(#xa9 #xa4) (run-src " adca ,y"))
(test "indexed-constant-null-offset-from-r-indirect"
'(#xa9 #xb8)
(run-src " adca [,y]"))
(test "indexed-constant-5bit-offset-from-r"
'(#xa9 #x30)
(run-src " adca -16,y"))
(test "indexed-constant-8bit-offset-from-r"
'(#xa9 #xa8 #x80)
(run-src " adca -128,y"))
(test "indexed-constant-16bit-offset-from-r"
'(#xa9 #xa9 #x80 #x00)
(run-src " adca -32768,y"))
(test "indexed-constant-8bit-offset-from-pc"
'(#xa9 #x8c #xf0)
(run-src " adca -16,pcr"))
(test "indexed-constant-16bit-offset-from-pc"
'(#xa9 #x8d #x80 #x00)
(run-src " adca -32768,pcr"))
(test "indexed-accumulator-offset-from-r" '(#xa9 #xa6) (run-src " adca a,y"))
(test "indexed-accumulator-offset-from-r-indirect"
'(#xa9 #xb6)
(run-src " adca [a,y]"))
(test "indexed-constant-8bit-offset-from-r-indirect"
'(#xa9 #xb8 #xf0)
(run-src " adca [-16,y]"))
(test "indexed-constant-16bit-offset-from-r-indirect"
'(#xa9 #xb9 #x80 #x00)
(run-src " adca [-32768,y]"))
(test "indexed-constant-8bit-offset-from-pc-indirect"
'(#xa9 #xfc #xf0)
(run-src " adca [-16,pcr]"))
(test "indexed-constant-16bit-offset-from-pc-indirect"
'(#xa9 #xfd #x80 00)
(run-src " adca [-32768,pcr]")))
(test-group
"Instructions"
(test "abx" '(#x3a) (run-src " abx"))
(test "adca" '(#x89 #xff) (run-src " adca #$ff"))
(test "adcb" '(#xc9 #xff) (run-src " adcb #$ff"))
(test "adda" '(#x8b #xff) (run-src " adda #$ff"))
(test "addb" '(#xcb #xff) (run-src " addb #$ff"))
(test "addd" '(#xc3 #xff #xfe) (run-src " addd #$fffe"))
(test "anda" '(#x84 #xff) (run-src " anda #$ff"))
(test "andb" '(#xc4 #xff) (run-src " andb #$ff"))
(test "asl" '(#x68 #xa1) (run-src " asl ,y++"))
(test "asla" '(#x48) (run-src " asla"))
(test "aslb" '(#x58) (run-src " aslb"))
(test "bcc" '(#x24 #x02) (run-src " bcc 2"))
(test "bcs" '(#x25 #x02) (run-src " bcs 2"))
(test "beq" '(#x27 #x02) (run-src " beq 2"))
(test "bge" '(#x2c #x02) (run-src " bge 2"))
(test "bgt" '(#x2e #x02) (run-src " bgt 2"))
(test "bhi" '(#x22 #x02) (run-src " bhi 2"))
(test "bhs" '(#x24 #x02) (run-src " bhs 2"))
(test "bita" '(#x85 #xff) (run-src " bita #$ff"))
(test "bitb" '(#xc5 #xff) (run-src " bitb #$ff"))
(test "ble" '(#x2f #x02) (run-src " ble 2"))
(test "blo" '(#x25 #x02) (run-src " blo 2"))
(test "bls" '(#x23 #x02) (run-src " bls 2"))
(test "blt" '(#x2d #x02) (run-src " blt 2"))
(test "bmi" '(#x2b #x02) (run-src " bmi 2"))
(test "bne" '(#x26 #x02) (run-src " bne 2"))
(test "bpl" '(#x2a #x02) (run-src " bpl 2"))
(test "bra" '(#x20 #x02) (run-src " bra 2"))
(test "brn" '(#x21 #x02) (run-src " brn 2"))
(test "bsr" '(#x8d #x02) (run-src " bsr 2"))
(test "bvc" '(#x28 #x02) (run-src " bvc 2"))
(test "bvs" '(#x29 #x02) (run-src " bvs 2"))
(test "clr" '(#x6f #xa1) (run-src " clr ,y++"))
(test "clra" '(#x4f) (run-src " clra"))
(test "clrb" '(#x5f) (run-src " clrb"))
(test "cmpa" '(#x81 #xff) (run-src " cmpa #$ff"))
(test "cmpb" '(#xc1 #xff) (run-src " cmpb #$ff"))
(test "cmpd" '(#x10 #x83 #xff #xfe) (run-src " cmpd #$fffe"))
(test "cmps" '(#x11 #x8c #xff #xfe) (run-src " cmps #$fffe"))
(test "cmpu" '(#x11 #x83 #xff #xfe) (run-src " cmpu #$fffe"))
(test "cmpx" '(#x8c #xff #xfe) (run-src " cmpx #$fffe"))
(test "cmpy" '(#x10 #x8c #xff #xfe) (run-src " cmpy #$fffe"))
(test "com" '(#x63 #xa1) (run-src " com ,y++"))
(test "coma" '(#x43) (run-src " coma"))
(test "comb" '(#x53) (run-src " comb"))
(test "cwai" '(#x3c #xff) (run-src " cwai #$ff"))
(test "daa" '(#x19) (run-src " daa"))
(test "dec" '(#x6a #xa1) (run-src " dec ,y++"))
(test "deca" '(#x4a) (run-src " deca"))
(test "decb" '(#x5a) (run-src " decb"))
(test "eora" '(#x88 #xff) (run-src " eora #$ff"))
(test "eorb" '(#xc8 #xff) (run-src " eorb #$ff"))
(test "exg" '(#x1e #x8b) (run-src " exg a,dp"))
(test "inc" '(#x6c #xa1) (run-src " inc ,y++"))
(test "inca" '(#x4c) (run-src " inca"))
(test "incb" '(#x5c) (run-src " incb"))
(test "jmp" '(#x6e #xa1) (run-src " jmp ,y++"))
(test "jsr" '(#xad #xa1) (run-src " jsr ,y++"))
(test "lbcc" '(#x10 #x24 #x02 #x00) (run-src " lbcc $200"))
(test "lbcs" '(#x10 #x25 #x02 #x00) (run-src " lbcs $200"))
(test "lbeq" '(#x10 #x27 #x02 #x00) (run-src " lbeq $200"))
(test "lbge" '(#x10 #x2c #x02 #x00) (run-src " lbge $200"))
(test "lbgt" '(#x10 #x2e #x02 #x00) (run-src " lbgt $200"))
(test "lbhi" '(#x10 #x22 #x02 #x00) (run-src " lbhi $200"))
(test "lbhs" '(#x10 #x24 #x02 #x00) (run-src " lbhs $200"))
(test "lble" '(#x10 #x2f #x02 #x00) (run-src " lble $200"))
(test "lblo" '(#x10 #x25 #x02 #x00) (run-src " lblo $200"))
(test "lbls" '(#x10 #x23 #x02 #x00) (run-src " lbls $200"))
(test "lblt" '(#x10 #x2d #x02 #x00) (run-src " lblt $200"))
(test "lbmi" '(#x10 #x2b #x02 #x00) (run-src " lbmi $200"))
(test "lbne" '(#x10 #x26 #x02 #x00) (run-src " lbne $200"))
(test "lbpl" '(#x10 #x2a #x02 #x00) (run-src " lbpl $200"))
(test "lbra" '(#x16 #x02 #x00) (run-src " lbra $200"))
(test "lbrn" '(#x10 #x21 #x02 #x00) (run-src " lbrn $200"))
(test "lbsr" '(#x17 #x02 #x00) (run-src " lbsr $200"))
(test "lbvc" '(#x10 #x28 #x02 #x00) (run-src " lbvc $200"))
(test "lbvs" '(#x10 #x29 #x02 #x00) (run-src " lbvs $200"))
(test "lda" '(#x86 #xff) (run-src " lda #$ff"))
(test "ldb" '(#xc6 #xff) (run-src " ldb #$ff"))
(test "ldd" '(#xcc #xff #xfe) (run-src " ldd #$fffe"))
(test "lds" '(#x10 #xce #xff #xfe) (run-src " lds #$fffe"))
(test "ldu" '(#xce #xff #xfe) (run-src " ldu #$fffe"))
(test "ldx" '(#x8e #xff #xfe) (run-src " ldx #$fffe"))
(test "ldy" '(#x10 #x8e #xff #xfe) (run-src " ldy #$fffe"))
(test "leas" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leau" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leax" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leay" '(#x32 #xa1) (run-src " leas ,y++"))
(test "lsl" '(#x68 #xa1) (run-src " lsl ,y++"))
(test "lsla" '(#x48) (run-src " lsla"))
(test "lslb" '(#x49) (run-src " lslb"))
(test "lsr" '(#x64 #xa1) (run-src " lsr ,y++"))
(test "lsra" '(#x44) (run-src " lsra"))
(test "lsrb" '(#x45) (run-src " lsrb"))
(test "mul" '(#x3d) (run-src " mul"))
(test "ncc" '(#x62 #xa1) (run-src " ncc ,y++"))
(test "ncca" '(#x42) (run-src " ncca"))
(test "nccb" '(#x52) (run-src " nccb"))
(test "neg" '(#x60 #xa1) (run-src " neg ,y++"))
(test "nega" '(#x40) (run-src " nega"))
(test "negb" '(#x50) (run-src " negb"))
(test "nop" '(#x12) (run-src " nop"))
(test "ora" '(#x8a #xff) (run-src " ora #$ff"))
(test "ora" '(#xca #xff) (run-src " orb #$ff"))
(test "orcc" '(#x1a #xff) (run-src " orcc #$ff"))
(test "page" '(#x10) (run-src " page 2"))
(test "pshs" '(#x34 #xff) (run-src " pshs cc,a,b,dp,x,y,u,pc"))
(test "pshu" '(#x36 #xff) (run-src " pshu cc,a,b,dp,x,y,s,pc"))
(test "puls" '(#x35 #xff) (run-src " puls cc,a,b,dp,x,y,u,pc"))
(test "pulu" '(#x37 #xff) (run-src " pulu cc,a,b,dp,x,y,s,pc"))
(test "reset" '(#x3e) (run-src " reset"))
(test "rol" '(#x69 #xa1) (run-src " rol ,y++"))
(test "rola" '(#x49) (run-src " rola"))
(test "rolb" '(#x59) (run-src " rolb"))
(test "ror" '(#x66 #xa1) (run-src " ror ,y++"))
(test "rora" '(#x46) (run-src " rora"))
(test "rorb" '(#x56) (run-src " rorb"))
(test "rti" '(#x3b) (run-src " rti"))
(test "rts" '(#x39) (run-src " rts"))
(test "sbca" '(#x82 #xff) (run-src " sbca #$ff"))
(test "sbcb" '(#xc2 #xff) (run-src " sbcb #$ff"))
(test "sex" '(#x1d) (run-src " sex"))
(test "sta" '(#xa7 #xa1) (run-src " sta ,y++"))
(test "stb" '(#xe7 #xa1) (run-src " stb ,y++"))
(test "std" '(#xed #xa1) (run-src " std ,y++"))
(test "sts" '(#x10 #xef #xa1) (run-src " sts ,y++"))
(test "stu" '(#xef #xa1) (run-src " stu ,y++"))
(test "stx" '(#xaf #xa1) (run-src " stx ,y++"))
(test "sty" '(#x10 #xaf #xa1) (run-src " sty ,y++"))
(test "swi" '(#x3f) (run-src " swi"))
(test "swi2" '(#x10 #x3f) (run-src " swi2"))
(test "swi3" '(#x11 #x3f) (run-src " swi3"))
(test "sync" '(#x13) (run-src " sync"))
(test "tfr" '(#x1f #x8b) (run-src " tfr a,dp"))
(test "tst" '(#x6d #xa1) (run-src " tst ,y++"))
(test "tsta" '(#x4d) (run-src " tsta"))
(test "tstb" '(#x5d) (run-src " tstb")))
(test-exit)
| false |
2ae28faad995c5489b59c0bceffe15cfba1239d8
|
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
|
/ext/crypto/math/prime.scm
|
b9ddcf1e37c2c5cc3efa39a69d0c3ea97556c2ec
|
[
"BSD-2-Clause"
] |
permissive
|
david135/sagittarius-scheme
|
dbec76f6b227f79713169985fc16ce763c889472
|
2fbd9d153c82e2aa342bfddd59ed54d43c5a7506
|
refs/heads/master
| 2016-09-02T02:44:31.668025 | 2013-12-21T07:24:08 | 2013-12-21T07:24:08 | 32,497,456 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,530 |
scm
|
prime.scm
|
;;
#!compatible
(library (math prime)
(export prime? ;; this is Scheme way, isn't it?
(rename (prime? is-prime?)) ;; backward compatibility
random-prime
lucas-lehmer?)
(import (rnrs)
(sagittarius control)
(sagittarius)
(math helper)
(math random))
(define *small-primes*
'(3 5 7 11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89 97 101
103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997))
(define (jacobi-symbol p n)
(define (discards-fact2 p u j)
(define (shift-p p)
(let loop ((p p))
(if (zero? (fxand p 3))
(loop (fxarithmetic-shift-right p 2))
p)))
(let ((p (shift-p p)))
(if (zero? (fxand p 1))
(let ((p (fxarithmetic-shift-right p 1)))
(values p (if (zero? (fxand
(fxxor u (fxarithmetic-shift-right u 1))
2))
j
(- j))))
(values p j)))) ;; 3 or 5 mod 8
(define (ensure-positive p u j)
(if (< p 0)
(let ((p (- p))
(n8 (fxand u 7)))
(values p (if (or (= n8 3) (= n8 7)) (- j) j)))
(values p j)))
(unless (fixnum? p)
(error 'jacobi-symbol "p is too big" p))
(if (or (zero? p) (even? n))
0
;; get the least significant word
(let ((u (bitwise-and n (greatest-fixnum))))
(let*-values (((tp tj) (ensure-positive p u 1))
((p j) (discards-fact2 tp u tj)))
(if (= p 1)
j
;; apply quadratic reciprocity (p = u = 3 (mod 4)
(let ((j (if (zero? (fxand p u 2)) j (- j)))
;; reduce u mod p
(u (mod u p)))
;; compute jacobi(u, p), u < p
(let loop ((u u) (p p) (j j))
(if (zero? u)
0
(let-values (((u j) (discards-fact2 u p j)))
(if (= u 1)
j
;; now both u and p are odd so use
;; quadratic reciprocity
(let-values (((u p j)
(if (< u p)
(values p u (if (zero?
(fxand u p 2))
(- j)
j))
(values u p j))))
(loop (mod u p) p j))))))))))))
;; Lucas-Lehmer prime test
(define (lucas-lehmer? n)
(define (lucas-lehmer-sequence z k n)
(define (compute-sub-shift t n)
(bitwise-arithmetic-shift-right (if (odd? t) (- t n) t) 1))
(let loop ((i (- (bitwise-length k) 2))
(u 1)
(v 1))
(if (< i 0)
u
(let ((u2 (mod (* u v) n))
(v2 (compute-sub-shift (mod (+ (* v v) (* z (* u u))) n) n)))
(if (bitwise-bit-set? k i)
(loop (- i 1)
(compute-sub-shift (mod (+ u2 v2) n) n)
(compute-sub-shift (mod (+ v2 (* z u2)) n) n))
(loop (- i 1) u2 v2))))))
(define (step1 n)
(do ((d 5 (if (< d 0) (+ (abs d) 2) (- (+ d 2)))))
((= (jacobi-symbol d n) -1) d)))
(let* ((d (step1 n))
(u (lucas-lehmer-sequence d (+ n 1) n)))
(zero? (mod u n))))
(define (miller-rabin? q k rand)
(define (check-small-prime q)
(let loop ((p *small-primes*))
(cond ((null? p) #f)
((zero? (mod q (car p))) #t)
(else
(loop (cdr p))))))
(let ((q (abs q)))
(cond ((even? q) #f) ;; obvious
((= q 1) #f) ;; 1 is not prime
((memv q *small-primes*) #t)
((check-small-prime q) #f) ;; multiple of small-primes
(else
;; Miller Rabin test
(let* ((t (- q 1))
(d (if (zero? (bitwise-and t 1))
(do ((d (bitwise-arithmetic-shift-right t 1)
(bitwise-arithmetic-shift-right d 1)))
((not (zero? (bitwise-and d 1))) d))
t)))
(let loop ((i 0))
(if (= i k)
#t
(let* ((a (+ (random rand (- q 2)) 1))
(t d)
(y (mod-expt a t q)))
;; check 0, ..., q - 1
(let loop2 ()
(when (and (not (= t (- q 1)))
(not (= y 1))
(not (= y (- q 1))))
(set! y (mod (* y y) q))
(set! t (bitwise-arithmetic-shift-left t 1))
(loop2)))
(if (and (not (= y (- q 1)))
(zero? (bitwise-and t 1)))
#f
(loop (+ i 1)))))))))))
;; Miller Rabin primality test
(define (prime? q :optional (k 50) (rand (secure-random RC4)))
(define bit-size (bitwise-length q))
(define try-count (cond ((< bit-size 100) 50)
((< bit-size 256) 27)
((< bit-size 512) 15)
((< bit-size 768) 8)
((< bit-size 1024) 4)
(else 2)))
(let ((n (min try-count k)))
(and (miller-rabin? q n rand)
(or (= try-count 50)
(lucas-lehmer? q))))
#;(miller-rabin? q k rand)
)
(define (random-prime size :key (prng (secure-random RC4)))
(let ((buf (make-bytevector size 0))
(index (- size 1)))
(let loop ()
(let* ((bv (read-random-bytes! prng buf size)))
(bytevector-u8-set!
bv 0 (bitwise-ior (bytevector-u8-ref bv 0) #x80 #x40))
(let ((b (bitwise-ior (bytevector-u8-ref bv index) #x01)))
(cond ((zero? (mod b 5)) (loop)) ;; ignore multiple number of 5
(else
(bytevector-u8-set! bv index b)
(let ((ret (bytevector->integer bv)))
(if (prime? ret)
ret
(loop))))))))))
)
| false |
58e6784a79284d006336b07ff8589ddade7a5d01
|
6b288a71553cf3d8701fe7179701d100c656a53c
|
/s/costctr.ss
|
6698409342b4bf53eb956f37596fe188afb49b5b
|
[
"Apache-2.0"
] |
permissive
|
cisco/ChezScheme
|
03e2edb655f8f686630f31ba2574f47f29853b6f
|
c048ad8423791de4bf650fca00519d5c2059d66e
|
refs/heads/main
| 2023-08-26T16:11:15.338552 | 2023-08-25T14:17:54 | 2023-08-25T14:17:54 | 56,263,501 | 7,763 | 1,410 |
Apache-2.0
| 2023-08-28T22:45:52 | 2016-04-14T19:10:25 |
Scheme
|
UTF-8
|
Scheme
| false | false | 6,810 |
ss
|
costctr.ss
|
;;; costctr.ss
;;; Copyright 1984-2017 Cisco Systems, Inc.
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(module ($cost-center)
(if-feature pthreads
(define-record-type ($cost-center $make-cost-center $cost-center?)
(fields
(mutable level)
(mutable instr-count)
(mutable alloc-count)
(mutable time-ns)
(mutable time-s)
(immutable mutex))
(nongenerative #{cost-center fgbx8g23emx4rf0txn2sr0-1})
(opaque #t)
(protocol
(lambda (new)
(lambda ()
(new (make-thread-parameter 0) 0 0 0 0 (make-mutex))))))
(define-record-type ($cost-center $make-cost-center $cost-center?)
(fields
(mutable level)
(mutable instr-count)
(mutable alloc-count)
(mutable time-ns)
(mutable time-s))
(nongenerative #{cost-center fgbx8g23emx4rf0txn2sr0-2})
(opaque #t)
(protocol
(lambda (new)
(lambda () (new 0 0 0 0 0))))))
(define-syntax cc-level
(lambda (x)
(syntax-case x ()
[(_ x)
(if-feature pthreads
#'(($cost-center-level x))
#'($cost-center-level x))])))
(define-syntax cc-level-set!
(lambda (x)
(syntax-case x ()
[(_ x v)
(if-feature pthreads
#'(($cost-center-level x) v)
#'($cost-center-level-set! x v))])))
(define $with-cost-center
(let ()
(define who 'with-cost-center)
(define-syntax with-mutex-if-threaded
(lambda (x)
(syntax-case x ()
[(_ mexp e0 e1 ...)
(if-feature pthreads
#'(with-mutex mexp e0 e1 ...)
#'(begin e0 e1 ...))])))
(define mod-
(lambda (x y)
(let ([r (- x y)])
(if (< r 0) (+ (expt 2 64) r) r))))
(lambda (timed? cc th)
(define-record-type saved
(sealed #t)
(nongenerative)
(fields (mutable alloc) (mutable intr) (mutable time)))
(unless ($cost-center? cc) ($oops who "~s is not a cost center" cc))
(unless (procedure? th) ($oops who "~s is not a procedure" th))
(let ([saved (make-saved 0 0 #f)])
(dynamic-wind #t
(lambda ()
(let ([level (cc-level cc)])
(cc-level-set! cc (fx+ level 1))
(when (fx= level 0)
(saved-alloc-set! saved ($object-ref 'unsigned-64 ($tc) (constant tc-alloc-counter-disp)))
(saved-intr-set! saved ($object-ref 'unsigned-64 ($tc) (constant tc-instr-counter-disp)))
(when timed? (saved-time-set! saved (current-time 'time-thread))))))
th
(lambda ()
(let ([level (cc-level cc)])
(cc-level-set! cc (fx- level 1))
(when (fx= level 1)
; grab time first -- to use up as little as possible
(let* ([curr-time (and timed? (current-time 'time-thread))]
[alloc-count (mod- ($object-ref 'unsigned-64 ($tc) (constant tc-alloc-counter-disp))
(saved-alloc saved))]
[instr-count (mod- ($object-ref 'unsigned-64 ($tc) (constant tc-instr-counter-disp))
(saved-intr saved))])
(with-mutex-if-threaded ($cost-center-mutex cc)
($cost-center-alloc-count-set! cc
(+ ($cost-center-alloc-count cc) alloc-count))
($cost-center-instr-count-set! cc
(+ ($cost-center-instr-count cc) instr-count))
(when timed?
(let ([saved-time (saved-time saved)])
(let-values ([(s ns) (let ([ns (- (time-nanosecond curr-time) (time-nanosecond saved-time))]
[s (- (time-second curr-time) (time-second saved-time))])
(if (< ns 0)
(values (- s 1) (+ ns (expt 10 9)))
(values s ns)))])
(let-values ([(s ns) (let ([ns (+ ($cost-center-time-ns cc) ns)]
[s (+ ($cost-center-time-s cc) s)])
(if (>= ns (expt 10 9))
(values (+ s 1) (- ns (expt 10 9)))
(values s ns)))])
($cost-center-time-s-set! cc s)
($cost-center-time-ns-set! cc ns)))))))))))))))
(set-who! cost-center-instruction-count
(lambda (cc)
(unless ($cost-center? cc) ($oops who "~s is not a cost center" cc))
($cost-center-instr-count cc)))
(set-who! cost-center-allocation-count
(lambda (cc)
(unless ($cost-center? cc) ($oops who "~s is not a cost center" cc))
(ash ($cost-center-alloc-count cc) (constant log2-ptr-bytes))))
(set-who! cost-center-time
(lambda (cc)
(unless ($cost-center? cc) ($oops who "~s is not a cost center" cc))
(make-time 'time-duration ($cost-center-time-ns cc) ($cost-center-time-s cc))))
(set-who! reset-cost-center!
(lambda (cc)
(unless ($cost-center? cc) ($oops who "~s is not a cost center" cc))
($cost-center-instr-count-set! cc 0)
($cost-center-alloc-count-set! cc 0)
($cost-center-time-s-set! cc 0)
($cost-center-time-ns-set! cc 0)))
(set! cost-center? (lambda (x) ($cost-center? x)))
(set! make-cost-center (lambda () ($make-cost-center)))
(set! with-cost-center
(rec with-cost-center
(case-lambda
[(cc th) ($with-cost-center #f cc th)]
[(timed? cc th) ($with-cost-center timed? cc th)])))
(record-writer (record-type-descriptor $cost-center)
(lambda (x p wr)
(let ([ns ($cost-center-time-ns x)] [s ($cost-center-time-s x)])
(fprintf p "#<cost center~[~2*~:; t=~d.~9,'0d~]~[~:; i=~:*~s~]~[~:; a=~:*~s~]>"
(+ ns s) s ns
($cost-center-instr-count x)
($cost-center-alloc-count x))))))
| true |
594bf2e897f8007d9d318e326c98c25baca15388
|
84c9e7520891b609bff23c6fa3267a0f7f2b6c2e
|
/2.89.scm
|
04b6af56718939dbde706fcaaa50720a2da55b34
|
[] |
no_license
|
masaedw/sicp
|
047a4577cd137ec973dd9a7bb0d4f58d29ef9cb0
|
11a8adf49897465c4d8bddb7e1afef04876a805d
|
refs/heads/master
| 2020-12-24T18:04:01.909864 | 2014-01-23T11:10:11 | 2014-01-23T11:17:38 | 6,839,863 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,287 |
scm
|
2.89.scm
|
(add-load-path ".")
(use sicp.ddp)
(use gauche.test)
;; 過去の実装を壊してないこと
(load "2.88")
(test-start "2.89")
(test* "add (make-polynomial-dense 'x '(5 3 0 5 1)) (make-polynomial-dense 'x '(1 2 3))"
(make-polynomial-dense 'x '(5 3 1 7 4))
(add (make-polynomial-dense 'x '(5 3 0 5 1)) (make-polynomial-dense 'x '(1 2 3)))
) ;; equ? はこの段階では未定義
(test* "negate (make-polynomial-dense 'x '(5 3 0 5 1))"
(make-polynomial-dense 'x '(-5 -3 0 -5 -1))
(negate (make-polynomial-dense 'x '(5 3 0 5 1)))
) ;; equ? はこの段階では未定義
(test* "sub (make-polynomial-dense 'x '(5 3 0 5 1)) (make-polynomial-dense 'x '(5 3 1 3 1))"
(make-polynomial-dense 'x '(0 0 -1 2 0))
(sub (make-polynomial-dense 'x '(5 3 0 5 1)) (make-polynomial-dense 'x '(5 3 1 3 1)))
) ;; equ? はこの段階では未定義
(test* "mul (make-polynomial-dense 'x '(5 1)) (make-polynomial-dense 'x '(1 2 3))"
(make-polynomial-dense 'x '(5 11 17 3))
(mul (make-polynomial-dense 'x '(5 1)) (make-polynomial-dense 'x '(1 2 3)))
) ;; equ? はこの段階では未定義
(test* "=zero? (make-polynomial-dense 'x '(0 0 0))"
#t
(=zero? (make-polynomial-dense 'x '(0 0 0)))
)
| false |
8a4485f9103ebacd78902f111f19d5eabf1e0307
|
4bd59493b25febc53ac9e62c259383fba410ec0e
|
/Scripts/Task/knuth-shuffle/scheme/knuth-shuffle-1.ss
|
ffdbefbb449711cf857de49e30a2001307f9ee60
|
[] |
no_license
|
stefanos1316/Rosetta-Code-Research
|
160a64ea4be0b5dcce79b961793acb60c3e9696b
|
de36e40041021ba47eabd84ecd1796cf01607514
|
refs/heads/master
| 2021-03-24T10:18:49.444120 | 2017-08-28T11:21:42 | 2017-08-28T11:21:42 | 88,520,573 | 5 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 502 |
ss
|
knuth-shuffle-1.ss
|
#!r6rs
(import (rnrs base (6))
(srfi :27 random-bits))
(define (semireverse li n)
(define (continue front back n)
(cond
((null? back) front)
((zero? n) (cons (car back) (append front (cdr back))))
(else (continue (cons (car back) front) (cdr back) (- n 1)))))
(continue '() li n))
(define (shuffle li)
(if (null? li)
()
(let
((li-prime (semireverse li (random-integer (length li)))))
(cons (car li-prime) (shuffle (cdr li-prime))))))
| false |
834bda6cc6bfee2e3c02cebdff1c7c3fe4f9aba2
|
19e1e43abea015add4edaa8257602da08cadedb5
|
/vulkan/structure-types.scm
|
2048925344bd672f7b8b60d4cc89efb9e2e7bf2a
|
[] |
no_license
|
corrodedlabs/phoenix
|
1f3f34d00e8426fc92b7bc814d5b640e7a8738d5
|
8a2974cc4e886a5276b7a14598c7a55642feec5a
|
refs/heads/master
| 2022-02-20T18:25:36.486934 | 2022-02-06T09:32:22 | 2022-02-06T09:32:22 | 226,878,975 | 6 | 0 | null | 2022-02-06T09:30:10 | 2019-12-09T13:33:16 |
Scheme
|
UTF-8
|
Scheme
| false | false | 21,421 |
scm
|
structure-types.scm
|
(trace-define-syntax define-enum-library
(lambda (stx)
(define (identifiers e*)
(let lp ((e* e*)
(ids '()))
(cond
((null? e*) ids)
(else
(syntax-case (car e*) ()
((e _) (lp (cdr e*)
(cons #'e ids)))
(e (lp (cdr e*)
(cons #'e ids))))))))
(syntax-case stx ()
((_ library-name enum-name e* ...)
(with-syntax (((e ...) (identifiers #'(e* ...))))
(syntax (library library-name
(export enum-name e ...)
(import (ffi))
(define-enum-ftype enum-name e* ...))))))))
(define-enum-library (vulkan structure-types) vk-structure-type
(application-info 0)
(instance-create-info 1)
(device-queue-create-info 2)
(device-create-info 3)
(submit-info 4)
(memory-allocate-info 5)
(mapped-memory-range 6)
(bind-sparse-info 7)
(fence-create-info 8)
(semaphore-create-info 9)
(event-create-info 10)
(query-pool-create-info 11)
(buffer-create-info 12)
(buffer-view-create-info 13)
(image-create-info 14)
(image-view-create-info 15)
(shader-module-create-info 16)
(pipeline-cache-create-info 17)
(pipeline-shader-stage-create-info 18)
(pipeline-vertex-input-state-create-info 19)
(pipeline-input-assembly-state-create-info 20)
(pipeline-tessellation-state-create-info 21)
(pipeline-viewport-state-create-info 22)
(pipeline-rasterization-state-create-info 23)
(pipeline-multisample-state-create-info 24)
(pipeline-depth-stencil-state-create-info 25)
(pipeline-color-blend-state-create-info 26)
(pipeline-dynamic-state-create-info 27)
(graphics-pipeline-create-info 28)
(compute-pipeline-create-info 29)
(pipeline-layout-create-info 30)
(sampler-create-info 31)
(descriptor-set-layout-create-info 32)
(descriptor-pool-create-info 33)
(descriptor-set-allocate-info 34)
(write-descriptor-set 35)
(copy-descriptor-set 36)
(framebuffer-create-info 37)
(render-pass-create-info 38)
(command-pool-create-info 39)
(command-buffer-allocate-info 40)
(command-buffer-inheritance-info 41)
(command-buffer-begin-info 42)
(render-pass-begin-info 43)
(buffer-memory-barrier 44)
(image-memory-barrier 45)
(memory-barrier 46)
(loader-instance-create-info 47)
(loader-device-create-info 48)
(physical-device-subgroup-properties 1000094000)
(bind-buffer-memory-info 1000157000)
(bind-image-memory-info 1000157001)
(physical-device-16bit-storage-features 1000083000)
(memory-dedicated-requirements 1000127000)
(memory-dedicated-allocate-info 1000127001)
(memory-allocate-flags-info 1000060000)
(device-group-render-pass-begin-info 1000060003)
(device-group-command-buffer-begin-info 1000060004)
(device-group-submit-info 1000060005)
(device-group-bind-sparse-info 1000060006)
(bind-buffer-memory-device-group-info 1000060013)
(bind-image-memory-device-group-info 1000060014)
(physical-device-group-properties 1000070000)
(device-group-device-create-info 1000070001)
(buffer-memory-requirements-info-2 1000146000)
(image-memory-requirements-info-2 1000146001)
(image-sparse-memory-requirements-info-2 1000146002)
(memory-requirements-2 1000146003)
(sparse-image-memory-requirements-2 1000146004)
(physical-device-features-2 1000059000)
(physical-device-properties-2 1000059001)
(format-properties-2 1000059002)
(image-format-properties-2 1000059003)
(physical-device-image-format-info-2 1000059004)
(queue-family-properties-2 1000059005)
(physical-device-memory-properties-2 1000059006)
(sparse-image-format-properties-2 1000059007)
(physical-device-sparse-image-format-info-2 1000059008)
(physical-device-point-clipping-properties 1000117000)
(render-pass-input-attachment-aspect-create-info 1000117001)
(image-view-usage-create-info 1000117002)
(pipeline-tessellation-domain-origin-state-create-info 1000117003)
(render-pass-multiview-create-info 1000053000)
(physical-device-multiview-features 1000053001)
(physical-device-multiview-properties 1000053002)
(physical-device-variable-pointers-features 1000120000)
(protected-submit-info 1000145000)
(physical-device-protected-memory-features 1000145001)
(physical-device-protected-memory-properties 1000145002)
(device-queue-info-2 1000145003)
(sampler-ycbcr-conversion-create-info 1000156000)
(sampler-ycbcr-conversion-info 1000156001)
(bind-image-plane-memory-info 1000156002)
(image-plane-memory-requirements-info 1000156003)
(physical-device-sampler-ycbcr-conversion-features 1000156004)
(sampler-ycbcr-conversion-image-format-properties 1000156005)
(descriptor-update-template-create-info 1000085000)
(physical-device-external-image-format-info 1000071000)
(external-image-format-properties 1000071001)
(physical-device-external-buffer-info 1000071002)
(external-buffer-properties 1000071003)
(physical-device-id-properties 1000071004)
(external-memory-buffer-create-info 1000072000)
(external-memory-image-create-info 1000072001)
(export-memory-allocate-info 1000072002)
(physical-device-external-fence-info 1000112000)
(external-fence-properties 1000112001)
(export-fence-create-info 1000113000)
(export-semaphore-create-info 1000077000)
(physical-device-external-semaphore-info 1000076000)
(external-semaphore-properties 1000076001)
(physical-device-maintenance-3-properties 1000168000)
(descriptor-set-layout-support 1000168001)
(physical-device-shader-draw-parameters-features 1000063000)
(swapchain-create-info-khr 1000001000)
(present-info-khr 1000001001)
(device-group-present-capabilities-khr 1000060007)
(image-swapchain-create-info-khr 1000060008)
(bind-image-memory-swapchain-info-khr 1000060009)
(acquire-next-image-info-khr 1000060010)
(device-group-present-info-khr 1000060011)
(device-group-swapchain-create-info-khr 1000060012)
(display-mode-create-info-khr 1000002000)
(display-surface-create-info-khr 1000002001)
(display-present-info-khr 1000003000)
(xlib-surface-create-info-khr 1000004000)
(xcb-surface-create-info-khr 1000005000)
(wayland-surface-create-info-khr 1000006000)
(android-surface-create-info-khr 1000008000)
(win32-surface-create-info-khr 1000009000)
(debug-report-callback-create-info-ext 1000011000)
(pipeline-rasterization-state-rasterization-order-amd 1000018000)
(debug-marker-object-name-info-ext 1000022000)
(debug-marker-object-tag-info-ext 1000022001)
(debug-marker-marker-info-ext 1000022002)
(dedicated-allocation-image-create-info-nv 1000026000)
(dedicated-allocation-buffer-create-info-nv 1000026001)
(dedicated-allocation-memory-allocate-info-nv 1000026002)
(physical-device-transform-feedback-features-ext 1000028000)
(physical-device-transform-feedback-properties-ext 1000028001)
(pipeline-rasterization-state-stream-create-info-ext 1000028002)
(image-view-handle-info-nvx 1000030000)
(texture-lod-gather-format-properties-amd 1000041000)
(stream-descriptor-surface-create-info-ggp 1000049000)
(physical-device-corner-sampled-image-features-nv 1000050000)
(external-memory-image-create-info-nv 1000056000)
(export-memory-allocate-info-nv 1000056001)
(import-memory-win32-handle-info-nv 1000057000)
(export-memory-win32-handle-info-nv 1000057001)
(win32-keyed-mutex-acquire-release-info-nv 1000058000)
(validation-flags-ext 1000061000)
(vi-surface-create-info-nn 1000062000)
(physical-device-texture-compression-astc-hdr-features-ext 1000066000)
(image-view-astc-decode-mode-ext 1000067000)
(physical-device-astc-decode-features-ext 1000067001)
(import-memory-win32-handle-info-khr 1000073000)
(export-memory-win32-handle-info-khr 1000073001)
(memory-win32-handle-properties-khr 1000073002)
(memory-get-win32-handle-info-khr 1000073003)
(import-memory-fd-info-khr 1000074000)
(memory-fd-properties-khr 1000074001)
(memory-get-fd-info-khr 1000074002)
(win32-keyed-mutex-acquire-release-info-khr 1000075000)
(import-semaphore-win32-handle-info-khr 1000078000)
(export-semaphore-win32-handle-info-khr 1000078001)
(d3d12-fence-submit-info-khr 1000078002)
(semaphore-get-win32-handle-info-khr 1000078003)
(import-semaphore-fd-info-khr 1000079000)
(semaphore-get-fd-info-khr 1000079001)
(physical-device-push-descriptor-properties-khr 1000080000)
(command-buffer-inheritance-conditional-rendering-info-ext 1000081000)
(physical-device-conditional-rendering-features-ext 1000081001)
(conditional-rendering-begin-info-ext 1000081002)
(physical-device-shader-float16-int8-features-khr 1000082000)
(present-regions-khr 1000084000)
(object-table-create-info-nvx 1000086000)
(indirect-commands-layout-create-info-nvx 1000086001)
(cmd-process-commands-info-nvx 1000086002)
(cmd-reserve-space-for-commands-info-nvx 1000086003)
(device-generated-commands-limits-nvx 1000086004)
(device-generated-commands-features-nvx 1000086005)
(pipeline-viewport-w-scaling-state-create-info-nv 1000087000)
(surface-capabilities-2-ext 1000090000)
(display-power-info-ext 1000091000)
(device-event-info-ext 1000091001)
(display-event-info-ext 1000091002)
(swapchain-counter-create-info-ext 1000091003)
(present-times-info-google 1000092000)
(physical-device-multiview-per-view-attributes-properties-nvx 1000097000)
(pipeline-viewport-swizzle-state-create-info-nv 1000098000)
(physical-device-discard-rectangle-properties-ext 1000099000)
(pipeline-discard-rectangle-state-create-info-ext 1000099001)
(physical-device-conservative-rasterization-properties-ext 1000101000)
(pipeline-rasterization-conservative-state-create-info-ext 1000101001)
(physical-device-depth-clip-enable-features-ext 1000102000)
(pipeline-rasterization-depth-clip-state-create-info-ext 1000102001)
(hdr-metadata-ext 1000105000)
(physical-device-imageless-framebuffer-features-khr 1000108000)
(framebuffer-attachments-create-info-khr 1000108001)
(framebuffer-attachment-image-info-khr 1000108002)
(render-pass-attachment-begin-info-khr 1000108003)
(attachment-description-2-khr 1000109000)
(attachment-reference-2-khr 1000109001)
(subpass-description-2-khr 1000109002)
(subpass-dependency-2-khr 1000109003)
(render-pass-create-info-2-khr 1000109004)
(subpass-begin-info-khr 1000109005)
(subpass-end-info-khr 1000109006)
(shared-present-surface-capabilities-khr 1000111000)
(import-fence-win32-handle-info-khr 1000114000)
(export-fence-win32-handle-info-khr 1000114001)
(fence-get-win32-handle-info-khr 1000114002)
(import-fence-fd-info-khr 1000115000)
(fence-get-fd-info-khr 1000115001)
(physical-device-performance-query-features-khr 1000116000)
(physical-device-performance-query-properties-khr 1000116001)
(query-pool-performance-create-info-khr 1000116002)
(performance-query-submit-info-khr 1000116003)
(acquire-profiling-lock-info-khr 1000116004)
(performance-counter-khr 1000116005)
(performance-counter-description-khr 1000116006)
(physical-device-surface-info-2-khr 1000119000)
(surface-capabilities-2-khr 1000119001)
(surface-format-2-khr 1000119002)
(display-properties-2-khr 1000121000)
(display-plane-properties-2-khr 1000121001)
(display-mode-properties-2-khr 1000121002)
(display-plane-info-2-khr 1000121003)
(display_plane-capabilities-2-khr 1000121004)
(ios-surface-create-info-mvk 1000122000)
(macos-surface-create-info-mvk 1000123000)
(debug-utils-object-name-info-ext 1000128000)
(debug-utils-object-tag-info-ext 1000128001)
(debug-utils-label-ext 1000128002)
(debug-utils-messenger-callback-data-ext 1000128003)
(debug-utils-messenger-create-info-ext 1000128004)
(android-hardware-buffer-usage-android 1000129000)
(android-hardware-buffer-properties-android 1000129001)
(android-hardware-buffer-format-properties-android 1000129002)
(import-android-hardware-buffer-info-android 1000129003)
(memory-get-android-hardware-buffer-info-android 1000129004)
(external-format-android 1000129005)
(physical-device-sampler-filter-minmax-properties-ext 1000130000)
(sampler-reduction-mode-create-info-ext 1000130001)
(physical-device-inline-uniform-block-features-ext 1000138000)
(physical-device-inline-uniform-block-properties-ext 1000138001)
(write-descriptor-set-inline-uniform-block-ext 1000138002)
(descriptor-pool-inline-uniform-block-create-info-ext 1000138003)
(sample-locations-info-ext 1000143000)
(render-pass-sample-locations-begin-info-ext 1000143001)
(pipeline-sample-locations-state-create-info-ext 1000143002)
(physical-device-sample-locations-properties-ext 1000143003)
(multisample-properties-ext 1000143004)
(image-format-list-create-info-khr 1000147000)
(physical-device-blend-operation-advanced-features-ext 1000148000)
(physical-device-blend-operation-advanced-properties-ext 1000148001)
(pipeline-color-blend-advanced-state-create-info-ext 1000148002)
(pipeline-coverage-to-color-state-create-info-nv 1000149000)
(pipeline-coverage-modulation-state-create-info-nv 1000152000)
(physical-device-shader-sm-builtins-features-nv 1000154000)
(physical-device-shader-sm-builtins-properties-nv 1000154001)
(drm-format-modifier-properties-list-ext 1000158000)
(drm-format-modifier-properties-ext 1000158001)
(physical-device-image-drm-format-modifier-info-ext 1000158002)
(image-drm-format-modifier-list-create-info-ext 1000158003)
(image-drm-format-modifier-explicit-create-info-ext 1000158004)
(image-drm-format-modifier-properties-ext 1000158005)
(validation-cache-create-info-ext 1000160000)
(shader-module-validation-cache-create-info-ext 1000160001)
(descriptor-set-layout-binding-flags-create-info-ext 1000161000)
(physical-device-descriptor-indexing-features-ext 1000161001)
(physical-device-descriptor-indexing-properties-ext 1000161002)
(descriptor-set-variable-descriptor-count-allocate-info-ext 1000161003)
(descriptor-set-variable-descriptor-count-layout-support-ext 1000161004)
(pipeline-viewport-shading-rate-image-state-create-info-nv 1000164000)
(physical-device-shading-rate-image-features-nv 1000164001)
(physical-device-shading-rate-image-properties-nv 1000164002)
(pipeline-viewport-coarse-sample-order-state-create-info-nv 1000164005)
(ray-tracing-pipeline-create-info-nv 1000165000)
(acceleration-structure-create-info-nv 1000165001)
(geometry-nv 1000165003)
(geometry-triangles-nv 1000165004)
(geometry-aabb-nv 1000165005)
(bind-acceleration-structure-memory-info-nv 1000165006)
(write-descriptor-set-acceleration-structure-nv 1000165007)
(acceleration-structure-memory-requirements-info-nv 1000165008)
(physical-device-ray-tracing-properties-nv 1000165009)
(ray-tracing-shader-group-create-info-nv 1000165011)
(acceleration-structure-info-nv 1000165012)
(physical-device-representative-fragment-test-features-nv 1000166000)
(pipeline-representative-fragment-test-state-create-info-nv 1000166001)
(physical-device-image-view-image-format-info-ext 1000170000)
(filter-cubic-image-view-image-format-properties-ext 1000170001)
(device-queue-global-priority-create-info-ext 1000174000)
(physical-device-shader-subgroup-extended-types-features-khr 1000175000)
(physical-device-8bit-storage-features-khr 1000177000)
(import-memory-host-pointer-info-ext 1000178000)
(memory-host-pointer-properties-ext 1000178001)
(physical-device-external-memory-host-properties-ext 1000178002)
(physical-device-shader-atomic-int64-features-khr 1000180000)
(physical-device-shader-clock-features-khr 1000181000)
(pipeline-compiler-control-create-info-amd 1000183000)
(calibrated-timestamp-info-ext 1000184000)
(physical-device-shader-core-properties-amd 1000185000)
(device-memory-overallocation-create-info-amd 1000189000)
(physical-device-vertex-attribute-divisor-properties-ext 1000190000)
(pipeline-vertex-input-divisor-state-create-info-ext 1000190001)
(physical-device-vertex-attribute-divisor-features-ext 1000190002)
(present-frame-token-ggp 1000191000)
(pipeline-creation-feedback-create-info-ext 1000192000)
(physical-device-driver-properties-khr 1000196000)
(physical-device-float-controls-properties-khr 1000197000)
(physical-device-depth-stencil-resolve-properties-khr 1000199000)
(subpass-description-depth-stencil-resolve-khr 1000199001)
(physical-device-compute-shader-derivatives-features-nv 1000201000)
(physical-device-mesh-shader-features-nv 1000202000)
(physical-device-mesh-shader-properties-nv 1000202001)
(physical-device-fragment-shader-barycentric-features-nv 1000203000)
(physical-device-shader-image-footprint-features-nv 1000204000)
(pipeline-viewport-exclusive-scissor-state-create-info-nv 1000205000)
(physical-device-exclusive-scissor-features-nv 1000205002)
(checkpoint-data-nv 1000206000)
(queue-family-checkpoint-properties-nv 1000206001)
(physical-device-timeline-semaphore-features-khr 1000207000)
(physical-device-timeline-semaphore-properties-khr 1000207001)
(semaphore-type-create-info-khr 1000207002)
(timeline-semaphore-submit-info-khr 1000207003)
(semaphore-wait-info-khr 1000207004)
(semaphore-signal-info-khr 1000207005)
(physical-device-shader-integer-functions-2-features-intel 1000209000)
(query-pool-create-info-intel 1000210000)
(initialize-performance-api-info-intel 1000210001)
(performance-marker-info-intel 1000210002)
(performance-stream-marker-info-intel 1000210003)
(performance-override-info-intel 1000210004)
(performance-configuration-acquire-info-intel 1000210005)
(physical-device-vulkan-memory-model-features-khr 1000211000)
(physical-device-pci-bus-info-properties-ext 1000212000)
(display-native-hdr-surface-capabilities-amd 1000213000)
(swapchain-display-native-hdr-create-info-amd 1000213001)
(imagepipe-surface-create-info-fuchsia 1000214000)
(metal-surface-create-info-ext 1000217000)
(physical-device-fragment-density-map-features-ext 1000218000)
(physical-device-fragment-density-map-properties-ext 1000218001)
(render-pass-fragment-density-map-create-info-ext 1000218002)
(physical-device-scalar-block-layout-features-ext 1000221000)
(physical-device-subgroup-size-control-properties-ext 1000225000)
(pipeline-shader-stage-required-subgroup-size-create-info-ext 1000225001)
(physical-device-subgroup-size-control-features-ext 1000225002)
(physical-device-shader-core-properties-2-amd 1000227000)
(physical-device-coherent-memory-features-amd 1000229000)
(physical-device-memory-budget-properties-ext 1000237000)
(physical-device-memory-priority-features-ext 1000238000)
(memory-priority-allocate-info-ext 1000238001)
(surface-protected-capabilities-khr 1000239000)
(physical-device-dedicated-allocation-image-aliasing-features-nv 1000240000)
(physical-device-separate-depth-stencil-layouts-features-khr 1000241000)
(attachment-reference-stencil-layout-khr 1000241001)
(attachment-description-stencil-layout-khr 1000241002)
(physical-device-buffer-device-address-features-ext 1000244000)
(buffer-device-address-create-info-ext 1000244002)
(physical-device-tool-properties-ext 1000245000)
(image-stencil-usage-create-info-ext 1000246000)
(validation-features-ext 1000247000)
(physical-device-cooperative-matrix-features-nv 1000249000)
(cooperative-matrix-properties-nv 1000249001)
(physical-device-cooperative-matrix-properties-nv 1000249002)
(physical-device-coverage-reduction-mode-features-nv 1000250000)
(pipeline-coverage-reduction-state-create-info-nv 1000250001)
(framebuffer-mixed-samples-combination-nv 1000250002)
(physical-device-fragment-shader-interlock-features-ext 1000251000)
(physical-device-ycbcr-image-arrays-features-ext 1000252000)
(physical-device-uniform-buffer-standard-layout-features-khr 1000253000)
(surface-full-screen-exclusive-info-ext 1000255000)
(surface-capabilities-full-screen-exclusive-ext 1000255002)
(surface-full-screen-exclusive-win32-info-ext 1000255001)
(headless-surface-create-info-ext 1000256000)
(physical-device-buffer-device-address-features-khr 1000257000)
(buffer-device-address-info-khr 1000244001)
(buffer-opaque-capture-address-create-info-khr 1000257002)
(memory-opaque-capture-address-allocate-info-khr 1000257003)
(device-memory-opaque-capture-address-info-khr 1000257004)
(physical-device-line-rasterization-features-ext 1000259000)
(pipeline-rasterization-line-state-create-info-ext 1000259001)
(physical-device-line-rasterization-properties-ext 1000259002)
(physical-device-host-query-reset-features-ext 1000261000)
(physical-device-index-type-uint8-features-ext 1000265000)
(physical-device-pipeline-executable-properties-features-khr 1000269000)
(pipeline-info-khr 1000269001)
(pipeline-executable-properties-khr 1000269002)
(pipeline-executable-info-khr 1000269003)
(pipeline-executable-statistic-khr 1000269004)
(pipeline-executable-internal-representation-khr 1000269005)
(physical-device-shader-demote-to-helper-invocation-features-ext 1000276000)
(physical-device-texel-buffer-alignment-features-ext 1000281000)
(physical-device-texel-buffer-alignment-properties-ext 1000281001))
| true |
6adaa718eb19443a9d31eaa1abbf253956c7d417
|
9f466767730a64747f02ee934138fcc88c93e1fe
|
/graph/base.scm
|
cadd76944f854a0571547d8f2ef0f0aec5c7ea90
|
[] |
no_license
|
lemvik/scheme-playground
|
81258bd3b5c847e019dfc6088ff1d806fe5dbc74
|
d32ab822857ecebd82ee28cd97bbbc07b1b56e3f
|
refs/heads/master
| 2021-01-25T04:58:15.536631 | 2017-06-16T13:32:13 | 2017-06-16T13:32:13 | 93,491,658 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,891 |
scm
|
base.scm
|
; -*- geiser-scheme-implementation: chez -*-
;;;;
;;;; Simple (immutable) graphs library.
;;;;
(library (graph base)
(export make-directed-graph
directed-graph?
directed-graph->list
depth-first-traversal
reverse-directed-graph
topological-sort)
(import (rnrs)
(utilities base))
;; Record containing graph structure.
(define-record-type (directed-graph allocate-directed-graph directed-graph?)
(nongenerative)
(fields (immutable adjacency-list))) ; The list stored is actually a hashtable
;; Condition to raise if there is a graph-related error.
(define-condition-type graph-error &condition make-graph-error graph-error?
(offending-vertex vertex) ; The vertex that caused the error, if any
(message message)) ; The description of the error.
;; Creates a graph from given list. List is assumed to be of form (adjacency list)
;; ((vertex-a (vertex-b vertex-c)) ...)
;; The representation of constructed graph is opaque.
;; NOTE: this function assumes equal? comparison and equal-hash hashing.
(define (make-directed-graph lst)
(allocate-directed-graph (normalize-directed-adjacency-list lst)))
;; Converts directed graph into a list
(define (directed-graph->list graph)
(let ([adj-list (directed-graph-adjacency-list graph)]
[result (list)])
(let-values ([(verts neighs) (hashtable-entries adj-list)])
(vector-for-each (lambda (k v)
(set! result (cons (list k v) result)))
verts
neighs)
result)))
;; Reverses the edges in a directed graph
(define (reverse-directed-graph graph)
(let ([new-adj-list (make-hashtable equal-hash equal?)]
[cur-adj-list (directed-graph-adjacency-list graph)])
(vector-for-each
(lambda (vert)
(unless (hashtable-contains? new-adj-list vert)
(hashtable-set! new-adj-list vert (list)))
(for-each
(lambda (neigh)
(hashtable-update! new-adj-list
neigh
(lambda (lst)
(cons vert lst))
(list)))
(directed-neighbours graph vert)))
(hashtable-keys cur-adj-list))
(allocate-directed-graph new-adj-list)))
;; Normalizes input adjacency list
;; Constructs new list where each vertex has a adjacency list (as input list does't necessarily do)
(define (normalize-directed-adjacency-list lst)
(let ([nodes (make-hashtable equal-hash equal?)])
(for-each (lambda (x)
(let ([vertex (car x)]
[neighbours (cadr x)])
(assert (list? neighbours))
(hashtable-set! nodes vertex neighbours)
(for-each (lambda (n)
(unless (hashtable-contains? nodes n)
(hashtable-set! nodes n (list))))
neighbours)))
lst)
nodes))
;; Returns neighbours of the vertex in a directed graph.
(define (directed-neighbours graph vert)
(let ([adj-list (directed-graph-adjacency-list graph)])
(hashtable-require adj-list vert (make-graph-error vert "Missing vertex from graph definition"))))
;; Traverses the graph depth-first invoking:
;; 1. pre-vertex - before the vertex or any of its neighbours is visited
;; 2. on-vertex - to process the vertex itself after it's neighbours were visited.
;; Since we cannot assume the input is a DAG, we keep a history of visited nodes.
(define (depth-first-traversal graph pre-vertex post-vertex)
(let* ([visited-nodes (make-hashtable equal-hash equal?)]
[adj-list (directed-graph-adjacency-list graph)]
[vertices (hashtable-keys adj-list)])
(define (visit vert)
(unless (hashtable-contains? visited-nodes vert)
(pre-vertex vert)
(hashtable-set! visited-nodes vert #t)
(for-each visit (directed-neighbours graph vert))
(post-vertex vert)))
(vector-for-each visit vertices)))
;; Topologically sort a given graph.
(define (topological-sort graph)
(let ([being-traversed-marks (make-hashtable equal-hash equal?)]
[result (list)])
(define (pre-visit! vert)
(when (hashtable-contains? being-traversed-marks vert)
(raise (make-graph-error vert "Not a directed-acyclic-graph, topological sort is impossible.")))
(hashtable-set! being-traversed-marks vert #t))
(define (post-visit! vert)
(set! result (cons vert result)))
(depth-first-traversal graph pre-visit! post-visit!)
result)))
| false |
708195c6f25fdc797c2dc6395ab7c90727be0c65
|
1ed47579ca9136f3f2b25bda1610c834ab12a386
|
/sec3/q3.40.scm
|
07298e99b571fcd58312a4333134f7d9e303a0bf
|
[] |
no_license
|
thash/sicp
|
7e89cf020e2bf5ca50543d10fa89eb1440f700fb
|
3fc7a87d06eccbe4dcd634406e3b400d9405e9c4
|
refs/heads/master
| 2021-05-28T16:29:26.617617 | 2014-09-15T21:19:23 | 2014-09-15T21:19:23 | 3,238,591 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 811 |
scm
|
q3.40.scm
|
;; 次の計算を実行した結果として取り得るxをすべて列挙せよ。
(define x 10)
(parallel-execute (lambda () (set! x (* x x)))
(lambda () (set! x (* x x x))))
;; P1: 参照, 参照, set.
;; P2: 参照, 参照, 参照, set.
;;
;; 逐次的に書き出すのは根気があればできるけど、一般的にできないもんかな。まいっか。
;; refP1 -> refP1 -> setP1 -> refP2 -> refP2 -> refP2 -> setP2
;; 10 10 100 100 100 100 1000000
;; refP1 -> refP1 -> refP2 -> refP2 -> refP2 -> setP2 -> setP1
;; ...
;;
;; refP1 refP1 setP1
;; refP2 refP2 refP2 setP2
;; トランプ的な。出せる順が決まっている。
;; a.rb
;; $x = $x * $x
;; b.rb
;; $x = $x * $x * $x
;;
;;
;; 例示は理解の試金石ってか。
| false |
94508feb2e908224defcaba1961fc1b65042cab3
|
4da2fdf33d85021ce3c5aa459ccc998cc3a6b95d
|
/c23.scm
|
451d2ef8cec9e4c96ac8fdcdb3d8f7e80425c1a6
|
[] |
no_license
|
pzel/sicp
|
7bdd9e5fa8648eff8fabdc80aad4df67d2c12618
|
99bace346cc1224724fe715644704f8889b2f6a9
|
refs/heads/master
| 2022-08-30T21:02:26.948669 | 2016-05-28T17:40:05 | 2016-05-28T17:40:05 | 7,996,775 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 12,621 |
scm
|
c23.scm
|
(use srfi-1)
(define (memq? sym x)
(cond ((null? x) #f)
((eq? sym (car x)) x)
(else
(memq? sym (cdr x)))))
; Exercise 2.54
(define (_equal? l1 l2)
(cond ((and (null? l1) (null? l2))
#t)
((and (atom? l1) (atom? l2))
(eq? l1 l2))
(else (and (_equal? (car l1) (car l2))
(_equal? (cdr l1) (cdr l2))))))
; 2.3.2 Symbolic Differentiation
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum (make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (multiplicand exp)
(deriv (multiplier exp) var))))
((expt? exp)
(make-product (exponent exp)
(make-product (make-expt (base exp)
(make-sum (exponent exp) -1))
(deriv (base exp) var))))
(else
(error "Unknown expression type -- DERIV" exp))))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (numbers? . vars)
(= (length (filter number? vars))
(length vars)))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1)
(variable? v2)
(eq? v1 v2)))
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((numbers? a1 a2) (+ a1 a2))
(else
(list '+ a1 a2))))
(define (sum? x) (and (pair? x) (eq? (car x) '+)))
(define (addend s) (cadr s))
(define (augend s)
(cond ((= 3 (length s)) (caddr s))
((> (length s) 3)
(cons '+
(cons (caddr s)
(cdddr s))))))
(define (make-product m1 m2 . ms)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((pair? ms)
(pp ms)(newline)
(list '* m1
(make-product m2 (car ms) (cdr ms))))
((=number? m1 1) m2)
((=number? m2 1) m1)
((numbers? m1 m2) (+ m1 m2))
(else (list '* m1 m2))))
(define (product? x) (and (pair? x) (eq? (car x) '*)))
(define (multiplier s) (cadr s))
(define (multiplicand s)
(cond ((= 3 (length s)) (caddr s))
((> (length s) 3)
(cons '*
(cons (caddr s)
(cdddr s))))))
(define (make-expt b e)
(cond ((=number? b 0) 0)
((=number? b 1) 1)
((=number? e 1) b)
((=number? e 0) 1)
((numbers? b e) (expt b e))
(else
(list '** b e))))
(define (expt? e) (and (pair? e) (eq? (car e) '**)))
(define (base e) (cadr e))
(define (exponent e) (caddr e))
;; Buildup to 2.59
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) set)
(else
(element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set s1 s2)
(cond ((or (null? s1) (null? s2)) '())
((element-of-set? (car s1) s2)
(cons (car s1)
(intersection-set (cdr s1) s2)))
(else
(intersection-set (cdr s1) s2))))
;; ex. 2.59
(define (union-set s1 s2)
(cond ((null? s1) s2)
((null? s2) s1)
((element-of-set? (car s1) s2)
(union-set (cdr s1) s2))
(else
(cons (car s1)
(union-set (cdr s1) s2)))))
;; ex 2.60
(define (elem-of-dset? x dset)
(cond ((null? dset) #f)
((equal? x (car dset)) #t)
(else
(elem-of-dset? x (cdr dset)))))
(define (adjoin-dset x dset)
(cons x dset))
(define (intersection-dset s1 s2)
(cond ((or (null? s1) (null? s2)) '())
((elem-of-dset? (car s1) s2)
(cons (car s1)
(intersection-dset (cdr s1) s2)))
(else
(intersection-dset (cdr s1) s2))))
(define (union-dset s1 s2)
(append s1 s2))
; buildup to 2.61
(define (oset . xs)
(sort xs <))
(define (elem-of-oset? x oset)
(cond ((null? oset) #f)
((< x (car oset)) #f)
((= x (car oset)) #t)
(else
(elem-of-oset? x (cdr oset)))))
(define (intersection-oset s1 s2)
(cond ((or (null? s1) (null? s2)) '())
((< (car s1) (car s2))
(intersection-oset (cdr s1) s2))
((> (car s1) (car s2))
(intersection-oset s1 (cdr s2)))
((= (car s1) (car s2))
(cons (car s1)
(intersection-oset (cdr s1) (cdr s2))))))
;; ex. 2.61
(define (adjoin-oset x s)
(cond ((null? s) (list x))
((< (car s) x)
(cons (car s)
(adjoin-oset x (cdr s))))
((> (car s) x)
(cons x s))
((= (car s) x) s)
(else (error "adjoin-oset failed for set: " s))))
;; ex. 2.62
(define (union-oset s1 s2)
(cond ((null? s1) s2)
((null? s2) s1)
((> (car s2) (car s1))
(cons (car s1)
(union-oset (cdr s1) s2)))
((< (car s2) (car s1))
(cons (car s2)
(union-set s1 (cdr s2))))
((= (car s1) (car s2))
(cons (car s1)
(union-oset (cdr s1) (cdr s2))))))
;; Sets as binary trees
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
(define (elem-of-tset? x set)
(cond ((null? set) #f)
((= x (entry set)) #t)
((> x (entry set))
(elem-of-tset? x (right-branch set)))
((< x (entry set))
(elem-of-tset? x (left-branch set)))))
(define (adjoin-tset x set)
(cond ((null? set) (make-tree x '() '()))
((= x (entry set)) set)
((> x (entry set))
(make-tree (entry set)
(left-branch set)
(adjoin-tset x (right-branch set))))
((< x (entry set))
(make-tree (entry set)
(adjoin-tset x (left-branch set))
(right-branch set)))))
;; Trees from Figure 2.16
(define (make-leaf x)
(make-tree x '() '()))
(define tree216-1
(make-tree 7
(make-tree 3
(make-leaf 1)
(make-leaf 5))
(make-tree 9
'()
(make-leaf 11))))
(define tree216-2
(make-tree 3
(make-leaf 1)
(make-tree 7
(make-leaf 5)
(make-tree 9
'()
(make-leaf 11)))))
(define tree216-3
(make-tree 5
(make-tree 3
(make-leaf 1)
'())
(make-tree 9
(make-leaf 7)
(make-leaf 11))))
;; Ex. 2.63
(define (tree->list1 tree)
(if (null? tree)
'()
(append (tree->list1 (left-branch tree))
(cons (entry tree)
(tree->list1 (right-branch tree))))))
(define (tree->list2 tree)
(define (copy-to-list tree result-list)
(if (null? tree)
result-list
(copy-to-list (left-branch tree)
(cons (entry tree)
(copy-to-list (right-branch tree) result-list)))))
(copy-to-list tree '()))
(define (make-tree1 this l r)
(make-tree this l r))
(define (list->bbtree elements)
(car (partial-tree (sort elements <) (length elements))))
(define (partial-tree elts n)
(if (= n 0)
(cons '() elts)
(let ((left-size (quotient (- n 1) 2)))
(let ((left-result (partial-tree elts left-size)))
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
(right-size (- n (+ 1 left-size))))
(let ((this-entry (car non-left-elts))
(right-result (partial-tree (cdr non-left-elts) right-size)))
(let ((right-tree (car right-result))
(remaining-elts (cdr right-result)))
(cons (make-tree1 this-entry left-tree right-tree)
remaining-elts))))))))
(define (bset xs)
(list->bbtree (sort (delete-duplicates xs)
<)))
(define (union-bset t1 t2)
(bset (append (tree->list1 t1)
(tree->list1 t2))))
(define (intersection-bset t1 t2)
(bset (intersection-oset (tree->list1 t1)
(tree->list1 t2))))
; 2.67
(define (key x) x)
(define (lookup given-key btree)
(cond ((null? btree) #f)
((< given-key (key (entry btree)))
(lookup given-key (left-branch btree)))
((> given-key (key (entry btree)))
(lookup given-key (right-branch btree)))
((eq? given-key (key (entry btree)))
(entry btree))
(else
(error "could not complete lookup"))))
;; 2.3.4 Huffman trees
(define (h-make-leaf symbol weight)
(list 'h-leaf symbol weight))
(define (h-leaf? object)
(and (pair? object)
(eq? (car object) 'h-leaf)))
(define (h-symbol-leaf o) (cadr o))
(define (h-weight-leaf o) (caddr o))
(define (h-make-tree left right)
(list left
right
(append (h-symbols left) (h-symbols right))
(+ (h-weight left) (h-weight right))))
(define (h-left-branch tree) (car tree))
(define (h-right-branch tree) (cadr tree))
(define (h-symbols tree)
(if (h-leaf? tree)
(list (h-symbol-leaf tree))
(caddr tree)))
(define (h-weight tree)
(if (h-leaf? tree)
(h-weight-leaf tree)
(cadddr tree)))
(define (h-decode bits tree)
(define (decode-1 bits current-branch)
(if (null? bits)
'()
(let ((next-branch (choose-next-branch (car bits) current-branch)))
(if (h-leaf? next-branch)
(cons (h-symbol-leaf next-branch)
(decode-1 (cdr bits) tree))
(decode-1 (cdr bits) next-branch)))))
(decode-1 bits tree))
(define (choose-next-branch bit branch)
(cond ((= 0 bit) (h-left-branch branch))
((= 1 bit) (h-right-branch branch))
(else (error "could not decode bit " bit))))
(define (h-adjoin-set x set)
(cond ((null? set) (list x))
((< (h-weight x) (h-weight (car set)))
(cons x set))
(else
(cons (car set)
(h-adjoin-set x (cdr set))))))
(define (h-make-leaf-set pairs)
(if (null? pairs)
'()
(let ((pair (car pairs)))
(h-adjoin-set (h-make-leaf (car pair)
(cadr pair))
(h-make-leaf-set (cdr pairs))))))
;; ex 2.67
(define sample-tree
(h-make-tree (h-make-leaf 'A 4)
(h-make-tree
(h-make-leaf 'B 2)
(h-make-tree
(h-make-leaf 'D 1)
(h-make-leaf 'C 1)))))
(define sample-message
'(0 1 1 0 0 1 0 1 0 1 1 1 0))
;; ex 2.68
(define (h-encode message tree)
(if (null? message)
'()
(append (h-encode-symbol (car message) tree)
(h-encode (cdr message) tree))))
(define (h-encode-symbol sym tree)
(cond ((or (null? tree) (h-leaf? tree))
'())
((memq? sym (h-symbols (h-left-branch tree)))
(cons 0 (h-encode-symbol sym (h-left-branch tree))))
((memq? sym (h-symbols (h-right-branch tree)))
(cons 1 (h-encode-symbol sym (h-right-branch tree))))
(else
(error sym " is not a member of the tree."))))
;; ex 2.69
(define (generate-h-tree pairs)
(successive-merge (h-make-leaf-set pairs)))
(define (successive-merge xs)
(cond ((null? xs) '())
((= 1 (length xs)) (car xs))
((= 2 (length xs))
(h-make-tree (cadr xs) (car xs)))
(else
(successive-merge (cons (h-make-tree (cadr xs) (car xs)) (cddr xs))))))
(define sample-pairs
'((A 4)
(B 2)
(D 1)
(C 1)))
;; ex. 2.70
(define song-pairs
'((a 2)
(na 16)
(boom 1)
(sha 3)
(get 2)
(yip 9)
(job 2)
(wah 1)))
(define song-tree (generate-h-tree song-pairs))
(define song-symbols
'( get a job
sha na na na na na na na na
get a job
sha na na na na na na na na
wah yip yip yip yip yip yip yip yip yip
sha boom ))
;; answer: huffman-encoding took 87 bits
;; fixed-length encoding would take (lg 8 = 3) * (36 symbols in song) == 108 bits
;; TODO: 2.71 (on paper)
| false |
f0c0242f3d1cb2169affb50f01c5a785ec7decca
|
3ecee09e72582189e8a4a48b3d85447c7927142f
|
/static/now/std__text__base58.scm
|
eb63b32a62bfea3f51c98dc6e2903577b5f933ff
|
[
"MIT"
] |
permissive
|
drewc/gx-quasar
|
6c745b9ec13c60ab6d1af8964a25ff14ceb4549b
|
17513967f611d46cc2d5a44999c90a7891e5d2d0
|
refs/heads/main
| 2023-02-02T17:01:12.011714 | 2020-12-18T22:18:19 | 2020-12-18T22:18:19 | 310,720,698 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,963 |
scm
|
std__text__base58.scm
|
(declare (block) (standard-bindings) (extended-bindings))
(begin
(declare (not safe))
(define std/text/base58#alphabet::t
(make-struct-type
'std/text/base58#alphabet::t
'#f
'2
'alphabet
'((final: . #t))
':init!
'(enc dec)))
(define std/text/base58#alphabet?
(make-struct-predicate std/text/base58#alphabet::t))
(define std/text/base58#make-alphabet
(lambda _$args165339_
(apply make-struct-instance std/text/base58#alphabet::t _$args165339_)))
(define std/text/base58#alphabet-enc
(make-struct-field-accessor std/text/base58#alphabet::t '0))
(define std/text/base58#alphabet-dec
(make-struct-field-accessor std/text/base58#alphabet::t '1))
(define std/text/base58#alphabet-enc-set!
(make-struct-field-mutator std/text/base58#alphabet::t '0))
(define std/text/base58#alphabet-dec-set!
(make-struct-field-mutator std/text/base58#alphabet::t '1))
(define std/text/base58#&alphabet-enc
(make-struct-field-unchecked-accessor std/text/base58#alphabet::t '0))
(define std/text/base58#&alphabet-dec
(make-struct-field-unchecked-accessor std/text/base58#alphabet::t '1))
(define std/text/base58#&alphabet-enc-set!
(make-struct-field-unchecked-mutator std/text/base58#alphabet::t '0))
(define std/text/base58#&alphabet-dec-set!
(make-struct-field-unchecked-mutator std/text/base58#alphabet::t '1))
(define std/text/base58#alphabet:::init!
(lambda (_self165326_ _str165327_)
(let* ((_alpha165329_ (string->list _str165327_))
(_enc165331_ (list->vector _alpha165329_))
(_dec165333_ (make-vector '128 '#f)))
(for-each
(lambda (_i165336_ _a165337_)
(vector-set! _dec165333_ (char->integer _a165337_) _i165336_))
(iota (string-length _str165327_))
_alpha165329_)
(if (##fx< '2 (##vector-length _self165326_))
(begin
(##vector-set! _self165326_ '1 _enc165331_)
(##vector-set! _self165326_ '2 _dec165333_))
(error '"struct-instance-init!: too many arguments for struct"
_self165326_)))))
(bind-method!
std/text/base58#alphabet::t
':init!
std/text/base58#alphabet:::init!
'#f)
(define std/text/base58#alphabet-encode
(lambda (_ab165200_ _i165201_)
(vector-ref
(##unchecked-structure-ref
_ab165200_
'1
std/text/base58#alphabet::t
'#f)
_i165201_)))
(define std/text/base58#alphabet-decode
(lambda (_ab165195_ _char165196_)
(let ((_i165198_ (char->integer _char165196_)))
(if (fx< _i165198_ '128)
(vector-ref
(##unchecked-structure-ref
_ab165195_
'2
std/text/base58#alphabet::t
'#f)
_i165198_)
'#f))))
(define std/text/base58#base58-btc-alphabet
(let ((__obj279788 (make-object std/text/base58#alphabet::t '2)))
(std/text/base58#alphabet:::init!
__obj279788
'"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
__obj279788))
(define std/text/base58#base58-flickr-alphabet
(let ((__obj279789 (make-object std/text/base58#alphabet::t '2)))
(std/text/base58#alphabet:::init!
__obj279789
'"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")
__obj279789))
(define std/text/base58#base58-encode__%
(lambda (_bytes165159_ _ab165160_)
(let* ((_idx165162_
(fx+ (fxquotient (fx* (u8vector-length _bytes165159_) '138) '100)
'1))
(_str165164_ (make-string _idx165162_)))
(let _lp165167_ ((_bn165169_
(std/text/base58#bytes->integer _bytes165159_))
(_idx165170_ _idx165162_))
(if (zero? _bn165169_)
(let ((_zero165172_
(std/text/base58#alphabet-encode _ab165160_ '0)))
(let _pad165174_ ((_i165176_ '0) (_idx165177_ _idx165170_))
(if (and (fx< _i165176_ (u8vector-length _bytes165159_))
(fxzero? (u8vector-ref _bytes165159_ _i165176_)))
(let ((_idx165179_ (fx- _idx165177_ '1)))
(string-set! _str165164_ _idx165179_ _zero165172_)
(_pad165174_ (fx+ _i165176_ '1) _idx165179_))
(substring
_str165164_
_idx165177_
(string-length _str165164_)))))
(let ((_bn165181_ (quotient _bn165169_ '58))
(_mo165182_ (modulo _bn165169_ '58))
(_idx165183_ (fx- _idx165170_ '1)))
(string-set!
_str165164_
_idx165183_
(std/text/base58#alphabet-encode _ab165160_ _mo165182_))
(_lp165167_ _bn165181_ _idx165183_)))))))
(define std/text/base58#base58-encode__0
(lambda (_bytes165188_)
(let ((_ab165190_ std/text/base58#base58-btc-alphabet))
(std/text/base58#base58-encode__% _bytes165188_ _ab165190_))))
(define std/text/base58#base58-encode
(lambda _g279791_
(let ((_g279790_ (##length _g279791_)))
(cond ((##fx= _g279790_ 1)
(apply std/text/base58#base58-encode__0 _g279791_))
((##fx= _g279790_ 2)
(apply std/text/base58#base58-encode__% _g279791_))
(else
(##raise-wrong-number-of-arguments-exception
std/text/base58#base58-encode
_g279791_))))))
(define std/text/base58#base58-decode__%
(lambda (_str165121_ _ab165122_)
(letrec* ((_leading-zeros165124_
(let ((_zero165142_
(std/text/base58#alphabet-encode _ab165122_ '0)))
(let _lp165144_ ((_i165146_ '0))
(if (and (fx< _i165146_ (string-length _str165121_))
(eq? _zero165142_
(string-ref _str165121_ _i165146_)))
(_lp165144_ (fx+ _i165146_ '1))
(make-u8vector _i165146_))))))
(let _lp165126_ ((_i165128_ '0) (_bn165129_ '0))
(if (fx< _i165128_ (string-length _str165121_))
(let* ((_char165131_ (string-ref _str165121_ _i165128_))
(_int165133_ (char->integer _char165131_))
(_g279792_
(if (fx< _int165133_ '128)
'#!void
(std/error#raise-io-error
'base58-decode
'"Invalid character"
_str165121_
_char165131_))))
(let ((_$e165137_
(std/text/base58#alphabet-decode
_ab165122_
_int165133_)))
(if _$e165137_
((lambda (_c165140_)
(_lp165126_
(fx+ _i165128_ '1)
(+ (* _bn165129_ '58) _c165140_)))
_$e165137_)
(std/error#raise-io-error
'base58-decode
'"Invalid character"
_str165121_
_char165131_))))
(u8vector-append
_leading-zeros165124_
(std/text/base58#integer->bytes _bn165129_)))))))
(define std/text/base58#base58-decode__0
(lambda (_str165151_)
(let ((_ab165153_ std/text/base58#base58-btc-alphabet))
(std/text/base58#base58-decode__% _str165151_ _ab165153_))))
(define std/text/base58#base58-decode
(lambda _g279794_
(let ((_g279793_ (##length _g279794_)))
(cond ((##fx= _g279793_ 1)
(apply std/text/base58#base58-decode__0 _g279794_))
((##fx= _g279793_ 2)
(apply std/text/base58#base58-decode__% _g279794_))
(else
(##raise-wrong-number-of-arguments-exception
std/text/base58#base58-decode
_g279794_))))))
(define std/text/base58#bytes->integer
(lambda (_bytes165111_)
(let _lp165113_ ((_i165115_ '0) (_r165116_ '0))
(if (fx< _i165115_ (u8vector-length _bytes165111_))
(let ((_b165118_ (u8vector-ref _bytes165111_ _i165115_)))
(_lp165113_
(fx+ _i165115_ '1)
(bitwise-ior (arithmetic-shift _r165116_ '8) _b165118_)))
_r165116_))))
(define std/text/base58#integer->bytes
(lambda (_x165104_)
(let _lp165106_ ((_x165108_ _x165104_) (_r165109_ '()))
(if (positive? _x165108_)
(_lp165106_
(arithmetic-shift _x165108_ '-8)
(cons (bitwise-and _x165108_ '255) _r165109_))
(list->u8vector _r165109_))))))
| false |
fd5a1021002436e810b2c6663a9b1d99d3a8a062
|
5e9de035f8ca12b0f937573adb3fa5c1a3777c1d
|
/hdt/test/hook.scm
|
f82bfa0625bf2893f848cddea86dcf224bb2f394
|
[
"MIT"
] |
permissive
|
her01n/htl
|
78fbfdc76450c10d55cf412d056f515fb32c756b
|
7601578d7c3ada0704e2f716f475fd6f4de7425b
|
refs/heads/master
| 2022-07-07T20:03:02.806965 | 2022-07-05T09:45:43 | 2022-07-05T09:45:43 | 205,449,424 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,235 |
scm
|
hook.scm
|
(define-module (test hook))
(use-modules (hdt hdt)
(test util))
(test hook
(define log "")
(execute-tests
(test
(hook
(set! log (string-append log "hook ")))
(set! log (string-append log "test "))))
(assert (equal? "test hook " log)))
(test hooks
(define log "")
(execute-tests
(test
(hook
(set! log (string-append log "first ")))
(hook
(set! log (string-append log "second ")))))
(assert (equal? "second first " log)))
(test hook-run-assert-failed
(define hook-run #f)
(execute-tests
(test
(hook (set! hook-run #t))
(assert #f)))
(assert hook-run))
(test hook-run-test-error
(define hook-run #f)
(execute-tests
(test
(hook (set! hook-run #t))
(error "test-error")))
(assert hook-run))
(test hook-run-previous-hook-error
(define hook-run #f)
(execute-tests
(test
(hook (set! hook-run #t))
(hook (error "test-error"))))
(assert hook-run))
(test hook-error-report
(define output
(with-output-to-string
(lambda ()
(run-tests
(collect-tests
(lambda () (test (hook (error "test-error")))))))))
(assert (string-contains output "test-error")))
| false |
a468f6f39d11cbffd762fd44fc5d48cc140e0b65
|
fb9a1b8f80516373ac709e2328dd50621b18aa1a
|
/ch2/2-5-3_hierarchies_of_types_in_symbolic_algebra.scm
|
cee503c92593157a4b9d320482fb98a44e364e19
|
[] |
no_license
|
da1/sicp
|
a7eacd10d25e5a1a034c57247755d531335ff8c7
|
0c408ace7af48ef3256330c8965a2b23ba948007
|
refs/heads/master
| 2021-01-20T11:57:47.202301 | 2014-02-16T08:57:55 | 2014-02-16T08:57:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 200 |
scm
|
2-5-3_hierarchies_of_types_in_symbolic_algebra.scm
|
; 拡張問題:有理関数
; 汎用算術演算システムを拡張し有理関数も含むようにする
; (x + 1) / (x^3 - 1)
; のような分子と分母が多項式の分数である
| false |
194a29daea9a74dc327bb5eea1da268b239a600a
|
961ccc58c2ed4ed1d84a78614bedf0d57a2f2174
|
/scheme/bigloo-bench.scm
|
b72e7105edd4e2871c4d5edce91eb44ded22f431
|
[] |
no_license
|
huangjs/mostly-lisp-code
|
96483b566b8fa72ab0b73bf0e21f48cdb80dab0d
|
9fe862dbb64f2a28be62bb1bd996238de018f549
|
refs/heads/master
| 2021-01-10T10:11:50.121705 | 2015-11-01T08:53:22 | 2015-11-01T08:53:22 | 45,328,850 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,754 |
scm
|
bigloo-bench.scm
|
;; A problem for which Bigloo excells.
;; Compile: bigloo -Obench -farithmetic -O3 matb.scm -o matb.exe
(module example
(main main)
(option (set! *genericity* #f))
(extern
(macro printf::int (::string ::double) "printf")
(clock::int () "clock")))
(define iii 0)
(define-macro ($ v c i j)
`(f64vector-ref ,v (+fx (*fx ,i ,c) ,j)) )
(define-macro ($! v c i j val)
`(f64vector-set! ,v (+fx (*fx ,i ,c) ,j) ,val))
(define-macro (!= x y)
`(not (=fx ,x ,y)))
(define (prt m r c)
(do ((i 0 (+fx i 1)))
((>=fx i r))
(newline)
(do ((j 0 (+fx j 1))) ((>=fx j c))
(printf " %4.3f " ($ m c i j)) )))
(define (make-system r)
(let* ((c (+fx r 1))
(m (make-f64vector (*fx r c) 0.0 ))
(xx 0.0)
(s 0.0))
(do ((i 0 (+fx i 1)) ) ((>=fx i r) m)
(set! s 0.0)
(do ((j 0 (+fx j 1)) ) ((>=fx j r) ($! m c i j s))
(set! xx (fixnum->flonum (random 3873)))
(set! s (+fl s xx))
($! m c i j xx ))) ))
(define-inline (swapit m c k l)
(let ((t 0.0))
(set! iii (+fx iii 1))
(do ((j 0 (+fx j 1))) ((>=fx j c))
(set! t ($ m c k j ))
($! m c k j ($ m c l j))
($! m c l j t)) ) )
(define-inline (find-max m c k i)
(do ((l (+fx k 1) (+fx l 1)))
((>=fx l (-fx c 1)) (when (!= i k) (swapit m c k i )))
(when (>fl (absfl ($ m c l k)) (absfl ($ m c i k)))
(set! i l)) ))
(define (solvit m r)
(let ((c (+fx r 1))
(rat 0.0)
(mkk 0.0))
(do ((k 0 (+fx k 1))) ((>=fx k (-fx r 1)))
(find-max m c k k)
(set! mkk ($ m c k k))
(do (( i (+fx k 1)(+fx i 1))) ((>=fx i r))
(set! rat (/fl ($ m c i k) mkk ))
(do ((j k (+fx j 1))) ((>=fx j c))
($! m c i j (-fl ($ m c i j)
(*fl rat ($ m c k j )) )))))
(do ((i (-fx r 1) (-fx i 1)) ) ((<fx i 0) m)
(do ((j (+fx i 1) (+fx j 1))
(tx 0.0 (-fl tx (*fl ($ m c i j)
($ m c j r )))))
((>=fx j r)
($! m c i r
(/fl (+fl ($ m c i r ) tx)
($ m c i i))) )))))
(define (elms argv)
(cond ((<fx (length argv) 2) 2000)
((string->number (cadr argv)) (string->number (cadr argv)))
(else 2000)))
(define (main argv)
(let* ((r (elms argv)) (c (+fx r 1)) (m (solvit (make-system r)
r)) )
(do ((i 0 (+fx i 1))) ((>=fx i (min r 10)))
(printf " %4.3f " ($ m c i r)) )
(newline) (display "Bigloo time= ") (display (clock))
(newline) (print "Number of swaps= " iii)))
| false |
e86c58471707d3a291f2285abfe3da44811c1d00
|
08b21a94e7d29f08ca6452b148fcc873d71e2bae
|
/src/loki/core/reader.sld
|
3661f79a485806e3e8b57aadd620a496ffd59047
|
[
"MIT"
] |
permissive
|
rickbutton/loki
|
cbdd7ad13b27e275bb6e160e7380847d7fcf3b3a
|
7addd2985de5cee206010043aaf112c77e21f475
|
refs/heads/master
| 2021-12-23T09:05:06.552835 | 2021-06-13T08:38:23 | 2021-06-13T08:38:23 | 200,152,485 | 21 | 1 |
NOASSERTION
| 2020-07-16T06:51:33 | 2019-08-02T02:42:39 |
Scheme
|
UTF-8
|
Scheme
| false | false | 36,568 |
sld
|
reader.sld
|
;; This is a port of the r7rs/r6rs reader located at:
;; https://github.com/weinholt/laesare
;; with r6rs support removed.
;;
;; Original License:
;; -*- mode: scheme; coding: utf-8 -*-
;; Copyright © 2017, 2018, 2019 Göran Weinholt <[email protected]>
;; SPDX-License-Identifier: MIT
;; Permission is hereby granted, free of charge, to any person obtaining a
;; copy of this software and associated documentation files (the "Software"),
;; to deal in the Software without restriction, including without limitation
;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;; and/or sell copies of the Software, and to permit persons to whom the
;; Software is furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;; DEALINGS IN THE SOFTWARE.
(define-library (loki core reader)
(import (scheme base))
(import (scheme char))
(import (scheme case-lambda))
(import (scheme file))
(import (loki util))
(import (loki path))
(import (loki core printer))
(import (loki core syntax))
(cond-expand
(loki (import (loki core exception)))
(gauche (import (only (gauche base) char-general-category))))
(cond-expand
(gauche (import (gauche base))
(import (scheme write))))
(import (srfi 69))
(export make-reader
read-annotated
read-datum
read-file
get-lexeme
reader-fold-case?-set!)
(begin
(cond-expand
(loki (define (char-general-category c) 'ZZ))
(else #f))
(define (is-identifier-char? c)
(or (char-ci<=? #\a c #\Z)
(char<=? #\0 c #\9)
(memv c '(#\! #\$ #\% #\& #\* #\/ #\: #\< #\= #\> #\? #\^ #\_ #\~
#\+ #\- #\. #\@ #\x200C #\x200D))
(and (> (char->integer c) 127)
(memq (char-general-category c) ;XXX: could be done faster
'(Lu Ll Lt Lm Lo Mn Nl No Pd Pc Po Sc Sm Sk So Co Nd Mc Me)))))
(define-syntax assert
(syntax-rules ()
((assert e)
(let ((e2 e))
(if e2 e2 (error "assertion failed" 'e))))))
(define (call-with-string-output-port proc)
(define port (open-output-string))
(proc port)
(get-output-string port))
(define *annotate* (make-parameter (lambda (type source datum) datum)))
;; Peek at the next char from the reader.
(define (lookahead-char reader)
(peek-char (reader-port reader)))
(define (get-next-char reader)
(read-char (reader-port reader)))
;; Get a char from the reader.
(define (get-char reader)
(let ((c (get-next-char reader)))
(when (eqv? c #\newline)
(reader-line-set! reader (+ (reader-line reader) 1))
(reader-column-set! reader -1))
(reader-column-set! reader (+ (reader-column reader) 1))
c))
;; Detects the (intended) type of Scheme source: r7rs-library,
;; r7rs-program, empty or unknown.
(define (detect-scheme-file-type port)
(let ((reader (make-reader port #f)))
(let-values (((type lexeme) (get-lexeme reader)))
(case type
((eof)
'empty)
((openp) ;a pair
(let-values (((type lexeme) (get-lexeme reader)))
(case type
((identifier)
(case lexeme
((import) 'r7rs-program)
((define-library) 'r7rs-library)
(else 'unknown)))
(else 'unknown))))
(else 'unknown)))))
(define-record-type <reader>
(make-reader-record
port file next-char line column saved-line saved-column fold-case? tolerant?)
reader?
(port reader-port)
(file reader-file)
(next-char reader-next-char reader-next-char-set!)
(line reader-line reader-line-set!)
(column reader-column reader-column-set!)
(saved-line reader-saved-line reader-saved-line-set!)
(saved-column reader-saved-column reader-saved-column-set!)
(fold-case? reader-fold-case? reader-fold-case?-set!)
(tolerant? reader-tolerant? reader-tolerant?-set!))
(define (make-reader port file)
(make-reader-record port file #f 1 0 1 0 #f #f))
(define (reader-mark reader)
(reader-saved-line-set! reader (reader-line reader))
(reader-saved-column-set! reader (reader-column reader)))
(define (reader-source reader)
(make-source (reader-file reader)
(reader-saved-line reader)
(reader-saved-column reader)))
(define-record-type <reference>
(make-reference label)
reference?
(label reference-label))
(define (read-annotated reader)
(parameterize ((*annotate* datum->annotation))
(read-datum reader)))
(define (read-datum reader)
(assert (reader? reader))
(let ((labels (make-labels)))
(let*-values (((type x) (get-lexeme reader))
((d) (handle-lexeme reader type x labels #f)))
(resolve-labels reader labels)
d)))
(define (read-file-from-reader reader)
(let f ((x (read-annotated reader)))
(if (and (annotation? x) (eof-object? (annotation-expression x)))
'()
(cons x (f (read-annotated reader))))))
(define (read-file fn fold-case?)
(let* ((path (wrap-path fn))
(str (path->string path))
(p (open-input-file str))
(reader (make-reader p str)))
(reader-fold-case?-set! reader fold-case?)
(let ((content (read-file-from-reader reader)))
content)))
;;; Lexeme reader
(define (reader-error reader msg . irritants)
;; Non-recoverable errors.
(raise (make-read-error msg (cons (reader-source reader) irritants))))
(define (reader-warning reader msg . irritants)
;; Recoverable if the reader is tolerant.
(if (reader-tolerant? reader)
(raise-continuable
(make-read-error msg (cons (reader-source reader) irritants)))
(raise (make-read-error msg (cons (reader-source reader) irritants)))))
(define (eof-warning reader)
(reader-warning reader "Unexpected EOF" (eof-object)))
(define (unicode-scalar-value? sv)
(and (<= 0 sv #x10FFFF)
(not (<= #xD800 sv #xDFFF))))
(define (char-delimiter? reader c)
;; Treats the eof-object as a delimiter
(or (eof-object? c)
(char-whitespace? c)
(memv c '(#\( #\) #\" #\; #\|))))
;; Get a line from the reader.
(define (get-line reader)
(call-with-string-output-port
(lambda (out)
(do ((c (get-char reader) (get-char reader)))
((or (eqv? c #\newline) (eof-object? c)))
(write-char c out)))))
;; Gets whitespace from the reader.
(define (get-whitespace reader char)
(call-with-string-output-port
(lambda (out)
(let lp ((char char))
(write-char char out)
(let ((char (lookahead-char reader)))
(when (and (char? char) (char-whitespace? char))
(lp (get-char reader))))))))
;; Get an inline hex escape (escaped character inside an identifier).
(define (get-inline-hex-escape p)
(reader-mark p)
(let lp ((digits '()))
(let ((c (get-char p)))
(cond ((eof-object? c)
(eof-warning p)
#\xFFFD)
((or (char<=? #\0 c #\9)
(char-ci<=? #\a c #\f))
(lp (cons c digits)))
((and (char=? c #\;) (pair? digits))
(let ((sv (string->number (list->string (reverse digits)) 16)))
(cond ((unicode-scalar-value? sv)
(integer->char sv))
(else
(reader-warning p "Inline hex escape outside valid range" sv)
#\xFFFD))))
(else
(reader-warning p "Invalid inline hex escape" c)
#\xFFFD)))))
(define (get-identifier p initial-char pipe-quoted?)
(let lp ((chars (if initial-char (list initial-char) '())))
(let ((c (lookahead-char p)))
(cond
((is-identifier-char? c)
(lp (cons (get-char p) chars)))
((and pipe-quoted? (char? c) (not (memv c '(#\| #\\))))
(lp (cons (get-char p) chars)))
((or (char-delimiter? p c) (and pipe-quoted? (eqv? c #\|)))
(when (eqv? c #\|)
(get-char p))
(let ((id (list->string (reverse chars))))
(if (reader-fold-case? p)
(values 'identifier (string->symbol (string-foldcase id)))
(values 'identifier (string->symbol id)))))
((char=? c #\\) ;\xUUUU;
(get-char p) ;consume #\\
(let ((c (get-char p))) ;should be #\x
(cond ((eqv? c #\x)
(lp (cons (get-inline-hex-escape p) chars)))
((and pipe-quoted?
(assv c '((#\" . #\")
(#\\ . #\\)
(#\a . #\alarm)
(#\b . #\backspace)
(#\t . #\tab)
(#\n . #\newline)
(#\r . #\return)
(#\| . #\|))))
=> (lambda (c) (lp (cons (cdr c) chars))))
(else
(if (eof-object? c)
(eof-warning p)
(reader-warning p "Invalid character following \\"))
(lp chars)))))
(else
(reader-warning p "Invalid character in identifier" c)
(get-char p)
(lp chars))))))
;; Get a number from the reader.
(define (get-number p initial-chars)
(let lp ((chars initial-chars))
(let ((c (lookahead-char p)))
(cond ((and (not (eqv? c #\#)) (char-delimiter? p c))
;; TODO: some standard numbers are not supported
;; everywhere, should use a number lexer.
(let ((str (list->string (reverse chars))))
(cond ((string->number str) =>
(lambda (num)
(values 'value num)))
;; TODO: This is incomplete.
((not (and (pair? initial-chars)
(char<=? #\0 (car initial-chars) #\9)))
(values 'identifier (string->symbol str)))
(else
(reader-warning p "Invalid number syntax" str)
(values 'identifier (string->symbol str))))))
(else
(lp (cons (get-char p) chars)))))))
;; Get a string datum from the reader.
(define (get-string p)
(let lp ((chars '()))
(let ((c (lookahead-char p)))
(cond ((eof-object? c)
(eof-warning p)
c)
((char=? c #\")
(get-char p)
(list->string (reverse chars)))
((char=? c #\\) ;escapes
(get-char p) ;consume #\\
(let ((c (lookahead-char p)))
(cond ((eof-object? c)
(eof-warning p)
c)
((or (memv c '(#\tab #\newline #\x85 #\x2028))
(eq? (char-general-category c) 'Zs))
;; \<intraline whitespace>*<line ending>
;; <intraline whitespace>*
(letrec ((skip-intraline-whitespace*
(lambda ()
(let ((c (lookahead-char p)))
(cond ((eof-object? c)
(eof-warning p)
c)
((or (char=? c '#\tab)
(eq? (char-general-category c) 'Zs))
(get-char p)
(skip-intraline-whitespace*))))))
(skip-newline
(lambda ()
(let ((c (get-char p)))
(cond ((eof-object? c) c)
((memv c '(#\newline #\x85 #\x2028)))
((char=? c #\return)
(when (memv (lookahead-char p)
'(#\newline #\x85))
(get-char p)))
(else
(reader-warning p "Expected a line ending" c)))))))
(skip-intraline-whitespace*)
(skip-newline)
(skip-intraline-whitespace*)
(lp chars)))
(else
(lp (cons
(case (get-char p)
((#\") #\")
((#\\) #\\)
((#\a) #\alarm)
((#\b) #\backspace)
((#\t) #\tab)
((#\n) #\newline)
((#\r) #\return)
((#\|) #\|)
((#\x) (get-inline-hex-escape p))
(else
(reader-warning p "Invalid escape in string" c)
#\xFFFD))
chars))))))
(else
(lp (cons (get-char p) chars)))))))
;; Gets a nested comment from the reader.
(define (get-nested-comment reader)
;; The reader is immediately after "#|".
(call-with-string-output-port
(lambda (out)
(let lp ((levels 1) (c0 (get-char reader)))
(let ((c1 (get-char reader)))
(cond ((eof-object? c0)
(eof-warning reader))
((and (eqv? c0 #\|) (eqv? c1 #\#))
(unless (eqv? levels 1)
(write-char c0 out)
(write-char c1 out)
(lp (- levels 1) (get-char reader))))
((and (eqv? c0 #\#) (eqv? c1 #\|))
(write-char c0 out)
(write-char c1 out)
(lp (+ levels 1) (get-char reader)))
(else
(write-char c0 out)
(lp levels c1))))))))
;; Get a comment from the reader (including the terminating whitespace).
(define (get-comment reader)
;; The reader is immediately after #\;.
(call-with-string-output-port
(lambda (out)
(let lp ()
(let ((c (get-char reader)))
(unless (eof-object? c)
(write-char c out)
(cond ((memv c '(#\newline #\x85 #\x2028 #\x2029)))
((char=? c #\return)
;; Weird line ending. This lookahead is what forces
;; the procedure to include the terminator.
(when (memv (lookahead-char reader) '(#\newline #\x85))
(write-char (get-char reader) out)))
(else
(lp)))))))))
;; Whitespace and comments can appear anywhere.
(define (atmosphere? type)
(memq type '(directive whitespace comment inline-comment nested-comment)))
;; Get the next lexeme from the reader, ignoring anything that is
;; like a comment.
(define (get-lexeme p)
(let-values (((type lexeme) (get-token p)))
(if (atmosphere? type)
(get-lexeme p)
(values type lexeme))))
;; Get the next token. Can be a lexeme, directive, whitespace or comment.
(define (get-token p)
(assert (reader? p))
(reader-mark p)
(let ((c (get-char p)))
(cond
((eof-object? c)
(values 'eof c))
((char-whitespace? c)
(values 'whitespace (get-whitespace p c)))
((char=? c #\;) ;a comment like this one
(values 'comment (get-comment p)))
((char=? c #\#) ;the mighty octothorpe
(let ((c (get-char p)))
(case c
((#\() (values 'vector #f))
((#\') (values 'abbrev 'syntax))
((#\`) (values 'abbrev 'quasisyntax))
((#\,)
(case (lookahead-char p)
((#\@)
(get-char p)
(values 'abbrev 'unsyntax-splicing))
(else (values 'abbrev 'unsyntax))))
((#\u #\U) ;r7rs
(let* ((c1 (and (eqv? (lookahead-char p) #\8) (get-char p)))
(c2 (and (eqv? c1 #\8) (eqv? (lookahead-char p) #\() (get-char p))))
(cond ((and (eqv? c1 #\8) (eqv? c2 #\())
(values 'bytevector #f))
(else
(reader-warning p "Expected #u8(")
(get-token p)))))
((#\;) ;s-expr/datum comment
(let lp ((atmosphere '()))
(let-values (((type token) (get-token p)))
(cond ((eq? type 'eof)
(eof-warning p)
(values 'inline-comment (cons (reverse atmosphere) p)))
((atmosphere? type)
(lp (cons (cons type token) atmosphere)))
(else
(let ((d (handle-lexeme p type token #f #t)))
(values 'inline-comment (cons (reverse atmosphere) d))))))))
((#\|) ;nested comment
(values 'nested-comment (get-nested-comment p)))
((#\!) ;#!r6rs etc
(let ((next-char (lookahead-char p)))
(cond ((and (= (reader-saved-line p) 1) (memv next-char '(#\/ #\space)))
(let ((line (reader-saved-line p))
(column (reader-saved-column p)))
(values 'shebang `(,line ,column ,(get-line p)))))
((and (char? next-char) (char-alphabetic? next-char))
(let-values (((type id) (get-token p)))
(cond
((eq? type 'identifier)
(case id
((fold-case) ;r6rs-app.pdf
(reader-fold-case?-set! p #t))
((no-fold-case) ;r6rs-app.pdf
(reader-fold-case?-set! p #f))
(else
(reader-warning p "Invalid directive" type id)))
(cond ((assq id '((false . #f) (true . #t)))
=> (lambda (x) (values 'value (cdr x))))
(else
(values 'directive id))))
(else
(reader-warning p "Expected an identifier after #!")
(get-token p)))))
(else
(reader-warning p "Expected an identifier after #!")
(get-token p)))))
((#\b #\B #\o #\O #\d #\D #\x #\X #\i #\I #\e #\E)
(get-number p (list c #\#)))
((#\t #\T)
(unless (char-delimiter? p (lookahead-char p))
(let* ((c1 (and (memv (lookahead-char p) '(#\r #\R)) (get-char p)))
(c2 (and c1 (memv (lookahead-char p) '(#\u #\U)) (get-char p)))
(c3 (and c2 (memv (lookahead-char p) '(#\e #\E)) (get-char p))))
(unless (and c1 c2 c3 (char-delimiter? p (lookahead-char p)))
(reader-warning p "Expected #true"))))
(values 'value #t))
((#\f #\F)
(unless (char-delimiter? p (lookahead-char p))
(let* ((c1 (and (memv (lookahead-char p) '(#\a #\A)) (get-char p)))
(c2 (and c1 (memv (lookahead-char p) '(#\l #\L)) (get-char p)))
(c3 (and c2 (memv (lookahead-char p) '(#\s #\S)) (get-char p)))
(c4 (and c3 (memv (lookahead-char p) '(#\e #\E)) (get-char p))))
(unless (and c1 c2 c3 c4 (char-delimiter? p (lookahead-char p)))
(reader-warning p "Expected #false" c1 c2 c3 c4))))
(values 'value #f))
((#\\)
(let lp ((char* '()))
(let ((c (lookahead-char p)))
(cond ((and (pair? char*) (char-delimiter? p c))
(let ((char* (reverse char*)))
(cond ((null? char*)
(reader-warning p "Empty character name")
(values 'value #\xFFFD))
((null? (cdr char*)) (values 'value (car char*)))
((char=? (car char*) #\x)
(cond ((for-each (lambda (c)
(or (char<=? #\0 c #\9)
(char-ci<=? #\a c #\f)))
(cdr char*))
(let ((sv (string->number (list->string (cdr char*)) 16)))
(cond ((unicode-scalar-value? sv)
(values 'value (integer->char sv)))
(else
(reader-warning p "Hex-escaped character outside valid range" sv)
(values 'value #\xFFFD)))))
(else
(reader-warning p "Invalid character in hex-escaped character"
(list->string (cdr char*)))
(values 'value #\xFFFD))))
(else
(let ((char-name (list->string char*))
(char-names '(("null" #\null)
("alarm" #\alarm)
("backspace" #\backspace)
("tab" #\tab)
("newline" #\newline)
("return" #\return)
("escape" #\escape)
("space" #\space)
("delete" #\delete))))
(cond
((or (assoc char-name char-names)
(and (reader-fold-case? p)
(assoc (string-foldcase char-name)
char-names)))
=> (lambda (char-data)
(values 'value (cadr char-data))))
(else
(reader-warning p "Invalid character name" char-name)
(values 'value #\xFFFD))))))))
((and (null? char*) (eof-object? c))
(eof-warning p)
(values 'value #\xFFFD))
(else
(lp (cons (get-char p) char*)))))))
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
(let lp ((char* (list c)))
(let ((next (lookahead-char p)))
(cond
((eof-object? next)
(eof-warning p)
(get-char p))
((char<=? #\0 next #\9)
(lp (cons (get-char p) char*)))
((char=? next #\=)
(get-char p)
(values 'label (string->number (list->string (reverse char*)) 10)))
((char=? next #\#)
(get-char p)
(values 'reference (string->number (list->string (reverse char*)) 10)))
(else
(reader-warning p "Expected #<n>=<datum> or #<n>#" next)
(get-token p))))))
(else
(reader-warning p "Invalid #-syntax" c)
(get-token p)))))
((char=? c #\")
(values 'value (get-string p)))
((memv c '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))
(get-number p (list c)))
((memv c '(#\- #\+)) ;peculiar identifier
(cond ((and (char=? c #\-) (eqv? #\> (lookahead-char p))) ;->
(get-identifier p c #f))
((char-delimiter? p (lookahead-char p))
(values 'identifier (if (eqv? c #\-) '- '+)))
(else
(get-number p (list c)))))
((char=? c #\.) ;peculiar identifier
(if (char-delimiter? p (lookahead-char p))
(values 'dot #f)
(get-number p (list c))))
((or (char-ci<=? #\a c #\Z) ;<constituent> and <special initial>
(memv c '(#\! #\$ #\% #\& #\* #\/ #\: #\< #\= #\> #\? #\^ #\_ #\~))
(or (eqv? c #\@) (memv c '(#\x200C #\x200D)))
(and (> (char->integer c) 127)
(memq (char-general-category c)
'(Lu Ll Lt Lm Lo Mn Nl No Pd Pc Po Sc Sm Sk So Co))))
(get-identifier p c #f))
((char=? c #\\) ;<inline hex escape>
(let ((c (get-char p)))
(cond ((eqv? c #\x)
(get-identifier p (get-inline-hex-escape p) #f))
(else
(cond ((eof-object? c)
(eof-warning p))
(else
(reader-warning p "Invalid character following \\")))
(get-token p)))))
(else
(case c
((#\() (values 'openp #f))
((#\)) (values 'closep #f))
;((#\[) (values 'openb #f))
;((#\]) (values 'closeb #f))
((#\') (values 'abbrev 'quote))
((#\`) (values 'abbrev 'quasiquote))
((#\,)
(case (lookahead-char p)
((#\@)
(get-char p)
(values 'abbrev 'unquote-splicing))
(else (values 'abbrev 'unquote))))
((#\|) (get-identifier p #f 'pipe))
(else
(reader-warning p "Invalid leading character" c)
(get-token p)))))))
;;; Datum reader
;; <datum> → <lexeme datum>
;; | <compound datum>
;; <lexeme datum> → <boolean> | <number>
;; | <character> | <string> | <symbol>
;; <symbol> → <identifier>
;; <compound datum> → <list> | <vector> | <bytevector>
;; <list> → (<datum>*) | [<datum>*]
;; | (<datum>+ . <datum>) | [<datum>+ . <datum>]
;; | <abbreviation>
;; <abbreviation> → <abbrev prefix> <datum>
;; <abbrev prefix> → ' | ` | , | ,@
;; | #' | #` | #, | #,@
;; <vector> → #(<datum>*)
;; <bytevector> → #vu8(<u8>*)
;; <u8> → 〈any <number> representing an exact
;; integer in {0, ..., 255}〉
(define (get-compound-datum p src terminator type labels)
(define vec #f) ;TODO: ugly, should be rewritten
(let lp ((head '()) (prev #f) (len 0))
(let-values (((lextype x) (get-lexeme p)))
(case lextype
((closep closeb eof)
(unless (eq? lextype terminator)
(if (eof-object? x)
(eof-warning p)
(reader-warning p "Mismatched parenthesis/brackets" lextype x terminator)))
(case type
((vector)
(let ((s (list->vector head)))
(set! vec s)
vec))
((list)
head)
((bytevector)
(apply bytevector (map annotation-expression head)))
(else
(reader-error p "Internal error in get-compound-datum" type))))
((dot) ;a dot like in (1 . 2)
(cond
((eq? type 'list)
(let*-values (((lextype x) (get-lexeme p))
((d) (handle-lexeme p lextype x labels #t)))
(let-values (((termtype __) (get-lexeme p)))
(cond ((eq? termtype terminator))
((eq? termtype 'eof)
(eof-warning p))
(else
(reader-warning p "Improperly terminated dot list"))))
(cond ((pair? prev)
(cond ((reference? d)
(register-reference p labels d
(lambda (d) (set-cdr! prev d))))
(else
(set-cdr! prev d))))
(else
(reader-warning p "Unexpected dot")))
head))
(else
(reader-warning p "Dot used in non-list datum")
(lp head prev len))))
(else
(let ((d (handle-lexeme p lextype x labels #t)))
(cond
((and (eq? type 'bytevector)
(or (reference? d)
(not (and (annotation? d)
(integer? (annotation-expression d))
(<= 0 (annotation-expression d) 255)))))
(reader-warning p "Invalid datum in bytevector" x)
(lp head prev len))
(else
(let ((new-prev (cons d '())))
(when (pair? prev)
(set-cdr! prev new-prev))
(when (reference? d)
(register-reference p labels d
(if (eq? type 'vector)
(lambda (d)
(vector-set! vec len d))
(lambda (d)
(set-car! new-prev d)))))
(if (pair? head)
(lp head new-prev (+ len 1))
(lp new-prev new-prev (+ len 1))))))))))))
(define (handle-lexeme p lextype x labels allow-refs?)
(let ((src (reader-source p)))
(case lextype
((openp)
(get-compound-datum p src 'closep 'list labels))
((vector)
(get-compound-datum p src 'closep 'vector labels))
((bytevector)
;; TODO: open-bytevector-output-port would be faster
(get-compound-datum p src 'closep 'bytevector labels))
((value eof identifier)
((*annotate*) lextype src x))
((abbrev)
(let-values (((type lex) (get-lexeme p)))
(cond ((eq? type 'eof)
(eof-warning p)
lex)
(else
(let ((d (handle-lexeme p type lex labels #t)))
(list ((*annotate*) 'identifier src x) d))))))
((label)
;; The object that follows this label can be referred
;; back from elsewhere.
(let*-values (((lextype lexeme) (get-lexeme p))
((d) (handle-lexeme p lextype lexeme labels allow-refs?)))
(register-label p labels x d)
d))
(else
(cond ((and allow-refs? (eq? lextype 'reference))
(make-reference x))
(else
;; Ignore the shebang ("#!/" or "#! " at the start of files).
;; FIXME: should only work for programs.
(unless (and (eq? lextype 'shebang) (eqv? (car x) 1) (eqv? (cadr x) 0))
(reader-warning p "Unexpected lexeme" lextype x))
(call-with-values
(lambda () (get-lexeme p))
(lambda (lextype x) (handle-lexeme p lextype x labels allow-refs?)))))))))
;;; Shared/circular data
(define (make-labels)
(make-hash-table eq?))
(define (register-label p labels label datum)
(when labels
(hash-table-update!/default labels label (lambda (old)
(when (car old)
(reader-warning p "Duplicate label" label))
(cons datum (cdr old)))
(cons #f '()))))
(define (register-reference _p labels reference setter)
(when labels
(hash-table-update!/default labels (reference-label reference) (lambda (old)
(cons (car old)
(cons setter (cdr old))))
(cons #f '()))))
(define (resolve-labels p labels)
(let ((entries (hash-table->alist labels)))
(for-each
(lambda (entry)
(let ((id (car entry))
(datum (cadr entry))
(refs (cddr entry)))
(unless datum
(reader-warning p "Missing label" id))
(for-each (lambda (ref) (ref datum))
refs)))
entries)))
(define (annotation-printer x writer out)
(let* ((source (annotation-source x))
(file (if source (source-file source) #f)))
(writer "#<syntax ")
(if source
(string-append
":"
(or file "<unknown>")
":"
(number->string (source-line source)) ":"
(number->string (source-column source)) " ")
" ")
(writer (annotation-expression x))
(writer ">")))
(cond-expand
(gauche
(define-method write-object ((self <annotation>) port)
(annotation-printer self (lambda (x . _) (write x port)) port))
(define (make-read-error message irritants)
(guard (error (else error))
(apply error message irritants)))))
(type-printer-set! <annotation> annotation-printer)
(type-printer-set! <source>
(lambda (x writer out)
(writer (string-append
(source-file x) ":"
(number->string (source-line x)) ":"
(number->string (source-column x))))))
))
| true |
612e57d8f966009b87a95c251ba89d17aacb5b95
|
bf1c9803ae38f9aad027fbe4569ccc6f85ba63ab
|
/chapter_2/2.1.Introduction.to.Data.Abstraction/ex_2.13.scm
|
8946ebd0072b29ff10fceaf3619646d9ed5a7b70
|
[] |
no_license
|
mehese/sicp
|
7fec8750d3b971dd2383c240798dbed339d0345a
|
611b09280ab2f09cceb2479be98ccc5403428c6c
|
refs/heads/master
| 2021-06-12T04:43:27.049197 | 2021-04-04T22:22:47 | 2021-04-04T22:23:12 | 161,924,666 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,420 |
scm
|
ex_2.13.scm
|
#lang sicp
(define (make-interval a b) (cons a b))
(define (lower-bound interval)
(car interval))
(define (upper-bound interval)
(cdr interval))
(define (width interval)
(/ (- (upper-bound interval) (lower-bound interval)) 2))
(define (make-center-width c w)
(make-interval (- c w) (+ c w)))
(define (center i)
(/ (+ (lower-bound i) (upper-bound i)) 2))
(define (tol i)
(let
((c (center i))
(l (lower-bound i))
(h (upper-bound i)))
(* (/ (abs (- c l)) c) 100.0)))
(define (make-center-percent c tol)
(let
((w (/ (* tol c) 100)))
(make-center-width c w)))
;; Old implementation
(define (mul-interval x y)
(let ((p1 (* (lower-bound x)
(lower-bound y)))
(p2 (* (lower-bound x)
(upper-bound y)))
(p3 (* (upper-bound x)
(lower-bound y)))
(p4 (* (upper-bound x)
(upper-bound y))))
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4))))
;; New implementation for approx multiplication
;; For positive numbers the product
;; (a1, b1) x (a2, b2) = (a1a2, b1b2)
;; And:
;; a1 = c1 - r1c1
;; b1 = c1 + r1c1
;; a2 = c2 - r2c2
;; b2 = c2 + r2c2
;; ⇒ a1a2 = c1c2(1 - r1 - r2 + r1r2)
;; b1b2 = c1c2(1 + r1 + r2 + r1r2)
(define (mul-approx x y)
(let
((c1 (center x))
(r1 (/ (tol x) 100))
(c2 (center y))
(r2 (/ (tol y) 100)))
(make-interval
(* c1 c2 (+ 1 (- r1) (- r2) (+ (* r1 r2))))
(* c1 c2 (+ 1 r1 r2 (* r1 r2))))))
;; Tolerance of product
;; tol = (a - c)/c [* 100 if you want percentages]
;; For a product of strictly positive intervals
;; c = (b - a)/2
;; = (c1c2(1 + r1 + r2 + r1r2) - c1c2(1 - r1 - r2 + r1r2))/2
;; = c1c2(1 + r1r2)
;; (a-c) = c1c2(1 - r1 - r2 + r1r2) - c1c2(1 + r1r2)
;; ⇒ r = (r1 + r2)/(1 + r1r2)
;; For very small tolerances
;; r1r2 ≃ 0
(define (tol-product x y)
(let
((r1 (/ (tol x) 100))
(r2 (/ (tol y) 100)))
(* 100 (/ (+ r1 r2) (+ 1 (* r1 r2))))))
;; r1r2 ≃ 0
(define (tol-approx-product x y)
(let
((r1 (/ (tol x) 100))
(r2 (/ (tol y) 100)))
(* 100 (+ r1 r2))))
(display "Compute the product and tolerance")
(newline)
(display "-------------------")
(newline)
(let
((i1 (make-center-percent 3.0 10.0))
(i2 (make-center-percent 15.0 5.0))
(i3 (make-center-percent 12.0 1.0))
(i4 (make-center-percent 8.5 1.25))
(i5 (make-center-percent 5.0 2.5))
(i6 (make-center-percent 20.0 0.5)))
(display (tol (mul-interval i1 i2)))
(newline)
(display (tol (mul-interval i2 i1)))
(newline)
(display (tol (mul-interval i1 i3)))
(newline)
(display (tol (mul-interval i5 i6)))
(newline)
(display (tol (mul-interval i3 i5)))
(newline)
(display (tol (mul-interval i6 i4)))
(newline)
(display (tol (mul-interval i2 i4)))
(newline)
(display (tol (mul-interval i5 i5)))
(newline))
(newline)
(display "Compute tolerance of product directly")
(newline)
(display "----------")
(newline)
(let
((i1 (make-center-percent 3.0 10.0))
(i2 (make-center-percent 15.0 5.0))
(i3 (make-center-percent 12.0 1.0))
(i4 (make-center-percent 8.5 1.25))
(i5 (make-center-percent 5.0 2.5))
(i6 (make-center-percent 20.0 0.5)))
(display (tol-product i1 i2))
(newline)
(display (tol-product i2 i1))
(newline)
(display (tol-product i1 i3))
(newline)
(display (tol-product i5 i6))
(newline)
(display (tol-product i3 i5))
(newline)
(display (tol-product i6 i4))
(newline)
(display (tol-product i2 i4))
(newline)
(display (tol-product i5 i5))
(newline))
(newline)
(display "Small intervals approx")
(newline)
(display "----------")
(newline)
(let
((i1 (make-center-percent 3.0 10.0))
(i2 (make-center-percent 15.0 5.0))
(i3 (make-center-percent 12.0 1.0))
(i4 (make-center-percent 8.5 1.25))
(i5 (make-center-percent 5.0 2.5))
(i6 (make-center-percent 20.0 0.5)))
(display (tol-approx-product i1 i2))
(newline)
(display (tol-approx-product i2 i1))
(newline)
(display (tol-approx-product i1 i3))
(newline)
(display (tol-approx-product i5 i6))
(newline)
(display (tol-approx-product i3 i5))
(newline)
(display (tol-approx-product i6 i4))
(newline)
(display (tol-approx-product i2 i4))
(newline)
(display (tol-approx-product i5 i5))
(newline))
| false |
3adbbacc1d4a3d132c719b3a09ad3bd9d1894e33
|
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
|
/src/scheme/compiler/codegen/tailcall.scm
|
ed50bfcb9d3d239641246ef64ea6baf5941806d9
|
[
"MIT"
] |
permissive
|
rtrusso/scp
|
e31ecae62adb372b0886909c8108d109407bcd62
|
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
|
refs/heads/master
| 2021-07-20T00:46:52.889648 | 2021-06-14T00:31:07 | 2021-06-14T00:31:07 | 167,993,024 | 8 | 1 |
MIT
| 2021-06-14T00:31:07 | 2019-01-28T16:17:18 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,456 |
scm
|
tailcall.scm
|
(define (scheme-codegen-continue-with-tail-call-varargs n-args-out)
(define (repeat-copy-arg times)
(if (zero? times)
(empty-insn-seq)
(append-insn-seq
(insn-seq '(accum)
'(accum index)
`((assign (reg index) (op load-array)
(reg accum) (const 0))
(push (reg index))
,@(if (> times 1)
'((assign (reg accum) (op sub-pointer)
(reg accum) (const 1)))
'())))
(repeat-copy-arg (- times 1)))))
(append-insn-seq
(insn-seq `(,(cadr (link-register)))
'(accum)
`((assign (reg accum) (op add-pointer) (sys stack-pointer)
(const ,(- n-args-out 1)))
(perform (op pop-frame))
(pop (reg index))
(assign (reg index) (op bit-lshift) (reg index)
(symconst shift-cells-per-word))
(assign (sys stack-pointer) (op add) (sys stack-pointer)
(reg index))))
(repeat-copy-arg n-args-out)
(insn-seq `(,(cadr (link-register)) ,(cadr (env-register)))
'() ;; all registers will be modified, but since this is a tail call it doesn't matter
`((assign (reg index) (const ,n-args-out))
(goto (reg operand))))))
| false |
5bbfe6e17e73caeb56807f62aad8613f5de86a0f
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/tests/unit-tests/00-check/check_true.scm
|
180c9b6fe3e8cd990c679988ab928900f2d4acd8
|
[
"Apache-2.0",
"LGPL-2.1-only"
] |
permissive
|
tomelam/gambit
|
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
|
d60fdeb136b2ed89b75da5bfa8011aa334b29020
|
refs/heads/master
| 2020-11-27T06:39:26.718179 | 2019-12-15T16:56:31 | 2019-12-15T16:56:31 | 229,341,552 | 1 | 0 |
Apache-2.0
| 2019-12-20T21:52:26 | 2019-12-20T21:52:26 | null |
UTF-8
|
Scheme
| false | false | 58 |
scm
|
check_true.scm
|
(include "#.scm")
(check-true #t)
(check-true (even? 0))
| false |
b1d182fa65c65934cc93fb3a350d1129bbedc0a2
|
1faa631fa173707f8482a6d05548b9c483ca5d99
|
/sicp/1.17.scm
|
43e4e8085bc8ee92d055cb5ab53f829c02f576a6
|
[
"Apache-2.0"
] |
permissive
|
localchart/exercises
|
4d02f65ff40a27c08edb408cf0e2c5ca467b7358
|
2aad9d25040774c43c31acac6f0bd5af3447e5a7
|
refs/heads/master
| 2021-01-01T03:57:24.138974 | 2016-12-29T02:26:29 | 2016-12-29T02:26:29 | 58,983,223 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 175 |
scm
|
1.17.scm
|
#lang racket
(require "sicp.rkt")
(define (xx a b)
(cond ((= b 0) 0)
((= b 1) a)
((even? b) (double (xx a (halve b))))
(else (+ a (xx a (- b 1))))))
| false |
342dd53979fa9a04708007cceffe005fdf32851e
|
784dc416df1855cfc41e9efb69637c19a08dca68
|
/src/bootstrap/gerbil/core__9.scm
|
71efc2da50bc340da44e2cce5ea55c33a3cbd024
|
[
"LGPL-2.1-only",
"Apache-2.0",
"LGPL-2.1-or-later"
] |
permissive
|
danielsz/gerbil
|
3597284aa0905b35fe17f105cde04cbb79f1eec1
|
e20e839e22746175f0473e7414135cec927e10b2
|
refs/heads/master
| 2021-01-25T09:44:28.876814 | 2018-03-26T21:59:32 | 2018-03-26T21:59:32 | 123,315,616 | 0 | 0 |
Apache-2.0
| 2018-02-28T17:02:28 | 2018-02-28T17:02:28 | null |
UTF-8
|
Scheme
| false | false | 5,501 |
scm
|
core__9.scm
|
(declare (block) (standard-bindings) (extended-bindings) (inlining-limit 200))
(begin
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41351_|
(gx#make-syntax-quote
'runtime-type-info::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41352_|
(gx#make-syntax-quote
'runtime-struct-info::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41353_|
(gx#make-syntax-quote
'runtime-class-info::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41354_|
(gx#make-syntax-quote
'expander-type-info::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41355_|
(gx#make-syntax-quote
'extended-runtime-type-info::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41356_|
(gx#make-syntax-quote
'extended-struct-info::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41357_|
(gx#make-syntax-quote
'extended-class-info::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41358_|
(gx#make-syntax-quote
'runtime-rtd-exhibitor::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41359_|
(gx#make-syntax-quote
'runtime-struct-exhibitor::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41360_|
(gx#make-syntax-quote
'runtime-class-exhibitor::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41361_|
(gx#make-syntax-quote
'macro-object::t
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41362_|
(gx#make-syntax-quote
'make-macro-object
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41363_|
(gx#make-syntax-quote 'macro-object? #f (gx#current-expander-context) '()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41364_|
(gx#make-syntax-quote
'macro-object-macro
#f
(gx#current-expander-context)
'()))
(define |gerbil/core$<MOP>$<MOP:3>[2]#_g41365_|
(gx#make-syntax-quote
'macro-object-macro-set!
#f
(gx#current-expander-context)
'()))
(begin
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#runtime-type-info|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41351_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#runtime-struct-info|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41352_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#runtime-class-info|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41353_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#expander-type-info|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41354_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#extended-runtime-type-info|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41355_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#extended-struct-info|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41356_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#extended-class-info|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41357_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#runtime-rtd-exhibitor|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41358_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#runtime-struct-exhibitor|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41359_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#runtime-class-exhibitor|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-runtime-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41360_|))
(define |gerbil/core$<MOP>$<MOP:3>[:1:]#macro-object|
(|gerbil/core$<MOP>$<MOP:2>[1]#make-extended-class-info|
'runtime-identifier:
|gerbil/core$<MOP>$<MOP:3>[2]#_g41361_|
'expander-identifiers:
(cons '()
(cons |gerbil/core$<MOP>$<MOP:3>[2]#_g41361_|
(cons |gerbil/core$<MOP>$<MOP:3>[2]#_g41362_|
(cons |gerbil/core$<MOP>$<MOP:3>[2]#_g41363_|
(cons (cons |gerbil/core$<MOP>$<MOP:3>[2]#_g41364_|
'())
(cons (cons |gerbil/core$<MOP>$<MOP:3>[2]#_g41365_|
'())
'()))))))
'type-exhibitor:
(##structure
|gerbil/core$<MOP>$<MOP:2>[1]#runtime-class-exhibitor::t|
'gerbil.core#macro-object::t
(list)
'macro-object
'#f
'()
'(macro))))))
| false |
fc8ac31b0a28692e205e5430c18212945bc164ca
|
de82217869618b0a975e86918184ecfddf701172
|
/reference/syntax-case/vantonder/macros-core.scm
|
b2b254f2a4f23e96b8af765255a94d249c378fb1
|
[] |
no_license
|
schemedoc/r6rs
|
6b4ef7fd87d8883d6c4bcc422b38b37f588e20f7
|
0009085469e47df44068873f834a0d0282648750
|
refs/heads/master
| 2021-06-18T17:44:50.149253 | 2020-01-04T10:50:50 | 2020-01-04T10:50:50 | 178,081,881 | 5 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 101,754 |
scm
|
macros-core.scm
|
;;;===============================================================================
;;;
;;; R6RS Macros and R6RS libraries:
;;;
;;; Copyright (c) 2006 Andre van Tonder
;;;
;;; Copyright statement at http://srfi.schemers.org/srfi-process.html
;;;
;;;===============================================================================
;;; September 13, 2006
;;;==========================================================================
;;;
;;; PORTABILITY:
;;; ------------
;;;
;;; Tested on MzScheme and Petite Chez
;;; (for the latter, simply change define-struct -> define-record).
;;;
;;; ---------------------------------------------------
;;; TO RUN: SIMPLY EXECUTE MACROS-TEST.SCM IN THE REPL.
;;; ---------------------------------------------------
;;;
;;; Uses following non-r5rs constructs, which should be simple
;;; to adapt to your r5rs implementation of choice:
;;;
;;; * define-struct
;;; * parameterize
;;; * let-values
;;;
;;;==========================================================================
;;;==========================================================================
;;;
;;; COMPATIBILITY WITH R6RS:
;;; ------------------------
;;;
;;; LIBRARIES:
;;;
;;; * TODO : Currently <library reference> must be = <library name>.
;;; Version matching is not yet implemented.
;;; * TODO : Exceptions are not yet raised if exported variables are set!
;;; * PERMITTED : A visit at one phase is a visit at all phases, and
;;; an invoke at one phase is an invoke at all phases
;;; * PERMITTED : Expansion of library form is started by removing all
;;; library bindings above phase 0
;;; * UNSPECIFIED : A syntax violation is raised if a binding is used outside
;;; its declared levels. This probably shouldn't be optional
;;; as it currently stands in the draft.
;;; * UNSPECIFIED : The phases available for an identifier are lexically
;;; determined from the identifier's source occurrence
;;; (see examples in maccros-test.scm)
;;; * UNSPECIFIED : Free-identifier=? is sensitive to levels, so it will give #t
;;; if and only if its arguments are interchangeable as references
;;; (not currently clear from specification).
;;; * EXTENSION : Negative import levels are allowed. For semantics, see below.
;;; For examples, see identifier-syntax in macros-derived.scm
;;; and various in macros-test.scm.
;;;
;;; SYNTAX-CASE:
;;;
;;; Currently, the r6rs syntax-case srfi is implemented, so any differences
;;; that may have been made between the srfi and the draft are not
;;; incorporated.
;;;
;;; * UNOBSERVABLE : We use a renaming algorithm instead of the mark/antimark
;;; algorithm described in the srfi. The difference should not
;;; be observable for correct macros.
;;; * UNSPECIFIED : A wrapped syntax object is the same as an unwrapped syntax object,
;;; and can be treated as unwrapped without an exception being raised.
;;; * EXTENSION : Quasisyntax is implemented with unquote/unquote-splicing.
;;; * EXTENSION : Syntax-error
;;;
;;;==========================================================================
;;;==========================================================================
;;;
;;; SEMANTICS OF NEGATIVE LEVELS:
;;; -----------------------------
;;;
;;; The implementation allows libraries to be imported at
;;; negative meta-level (an extension to the draft).
;;;
;;; However, when there are no negative level imports in a program,
;;; THE SEMANTICS COINCIDE WITH THAT DESCRIBED IN THE R6RS DRAFT.
;;;
;;; The full semantics implemented here, which is equivalent to R6RS when there
;;; are no negative levels, is as follows:
;;;
;;; To visit a library at level n: [ONLY FIRST BULLET IS NEW]
;;;
;;; * If n < 0 : Do nothing
;;; * If n >= 0 : * Visit at level (n + k) any library that is imported by
;;; this library for (meta k) and that has not yet been visited
;;; at level (n + k).
;;; * For each k >= 1, invoke at level (n + k) any library that is
;;; imported by this library for .... (meta k), and that has not
;;; yet been invoked at level (n + k).
;;; * Evaluate all syntax definitions in the library.
;;;
;;; To invoke a library at level n: [ONLY FIRST AND LAST BULLETS ARE NEW]
;;;
;;; * If n < 0 : Do nothing.
;;; * If n >= 0 : * Invoke at level (n + k) any library that is imported by this
;;; library for (meta k), and that has not yet been invoked
;;; at level (n + k).
;;; * If n = 0: Evaluate all variable definitions and expressions in
;;; the library.
;;; * If n > 0: Do nothing
;;;
;;; Runtime execution of a library happens in a fresh environment but is
;;; otherwise the same as invoking it at level 0.
;;;
;;; Fresh environments are created at the start of each
;;; of the two times (expansion and execution), and not for each of
;;; the possibly many meta-levels. During expansion, every binding
;;; is shared only between whichever levels it is imported into.
;;; A syntax violation is raised if a binding is used outside
;;; its declared levels.
;;;
;;;==========================================================================
;;;==========================================================================
;;;
;;; Hooks:
;;;
;;;==========================================================================
;; This generate-name will work on most Schemes,
;; BUT ONLY for whole-program expansion or continuous REPL sessions.
;;
;; Before any incremental compilation is attempted, it is essential
;; that this be redone to generate a symbol that
;;
;; - is read-write invariant,
;; - has a globally unique external representation.
;;
;; I believe the Chez gensym does this and can therefore be used
;; to attain reliable incremental and separate compilation.
;; On other systems, given access to the current seconds, a good approximation
;; to a reliable /single/ machine unique identifier may be obtained by
;; defining the seed to be
;;
;; (* (current-seconds) integer-larger-than-machine-cycles-per-second)).
;;
;; To make it globally unique, a machine id should then be incorporated.
(define (seed) 0)
(define generate-name
(let ((count (seed)))
(lambda (symbol)
(set! count (+ 1 count))
(string->symbol
(string-append (symbol->string symbol)
"|"
(number->string count))))))
;; Make-free-name is used to generate user program toplevel
;; names.
;;
;; The results of make-free-name must be disjoint from:
;;
;; - the results of generate-name
;; - all primitive and system bindings, including those
;; defined in this expander.
;; - all symbols that may appear in user programs.
;;
;; This is essential to ensure that there is no interference between
;; user and system namespaces, and to ensure the integrity of expanded
;; code generated by this expander.
;;
;; This default implementation is pretty much the best we can do in r5rs
;; but not quite robust for the following reason. While it is unlikely
;; that the character "|" will appear in hand-typed symbols in user programs,
;; it should be noted that if they do (which becomes possible in R6RS), or
;; if a program contains machine-generated symbols such as uuids,
;; the expanded code may be defective.
(define (make-free-name symbol level)
(string->symbol
(string-append "top|"
(symbol->string symbol)
"|"
(number->string level))))
;; This transforms to the equivalent of letrec*, which will be
;; correct but host compiler may already have a native letrec*
;; with special optimizations and error checks, in which case
;; you should just construct that.
;; Each def must be of the form (symbol . expression)
(define (build-primitive-lambda formals defs exps)
`(lambda ,formals
((lambda ,(map car defs)
,@(map (lambda (def) `(set! ,(car def) ,(cdr def)))
defs)
,@exps)
,@(map (lambda (def) `(unspecified))
defs))))
;;;==========================================================================
;;;
;;; End of hooks:
;;;
;;;==========================================================================
;;;==========================================================================
;;;
;;; Identifiers:
;;;
;;;==========================================================================
;; Name: The symbolic name of the identifier in the source.
;; Colour: See below for the colour data type.
;; Transformer-environment: The transformer environment is defined as the lexical
;; bindings valid during expansion (not execution) of the
;; |syntax| expression introducing the identifier.
;; Maps symbolic names of like-coloured identifiers
;; to their binding names (also symbols) in this
;; environment.
;; If it were not for datum->syntax, only the
;; binding of the containing identifier would be needed.
;; However, datum->syntax requires that we save the bindings
;; of all like-coloured identifiers.
;; The transformer environment may have been reflected, i.e.,
;; converted to a key that provides a concise representation
;; for inclusion in object code and allows destructive
;; retrospective updating of its bindings, needed for correct
;; expansion of bodies.
;; See the procedures binding-name, datum->syntax and
;; syntax-reflect for further clarification.
;; Level-correction: Integer that keeps track of shifts in meta-levels that may
;; occur when importing libraries.
(define-struct identifier (name
colours
transformer-env
level-correction))
(define (bound-identifier=? x y)
(check x identifier? 'bound-identifier=?)
(check y identifier? 'bound-identifier=?)
(and (eq? (identifier-name x)
(identifier-name y))
(colours=? (identifier-colours x)
(identifier-colours y))))
(define (free-identifier=? x y)
(check x identifier? 'free-identifier=?)
(check y identifier? 'free-identifier=?)
(eq? (binding-name x)
(binding-name y)))
;; The meta-level for the current expansion step:
(define *level* (make-parameter 0))
(define (correct-level id)
(- (*level*)
(identifier-level-correction id)))
;; A lexical or toplevel binding is of the form
;;
;; (<binding symbol> . <levels>)
;;
;; where <binding symbol> is the denotation and
;;
;; <levels> ::= (<uinteger> ...)
;;
;; lists the meta-levels at which the binding
;; is valid.
(define make-binding cons)
(define binding-symbol car)
(define binding-levels cdr)
;; Returns binding name of id if bound at the appropriate level.
;; If unbound or binding invalid at appropriate level (displaced),
;; returns a free name that incorporates the level.
;; If checked-use? is #t, throws syntax error if displaced.
(define (resolve-binding-name id checked-use?)
(let ((probe (lookup-binding id))
(level (correct-level id)))
(if probe
(let ((binding (cdr probe)))
(if (memv level (binding-levels binding))
(binding-symbol binding)
(if checked-use?
(syntax-error "Attempt to use binding of" id "at invalid level" level
": Binding is only valid at levels" (binding-levels binding))
(free-name id level))))
(begin
(if checked-use?
(syntax-warning "Reference to unbound identifier" id))
(free-name id level)))))
(define (lookup-binding id)
(or (lookup-usage-env id)
(lookup-transformer-env id)))
(define (free-name id level)
(make-free-name (identifier-name id) level))
;; For uses:
(define (checked-binding-name id)
(resolve-binding-name id #t))
;; For non-uses, such as free-identifier? predicates.
(define (binding-name id)
(resolve-binding-name id #f))
;; Generates a local binding entry at the current meta-level,
;; that can be added to the usage environment.
;; Returns
;; (<identifier> . <binding>)
(define (add-local-binding id)
(cons id
(make-binding (generate-name (identifier-name id))
(list (correct-level id)))))
;; Toplevel binding forms use as binding name the free name
;; if the identifier has no colour (was present in the source)
;; so that source-level forward references will work.
;; Otherwise a fresh identifier is generated.
;; This causes binding names in macro-generated toplevel
;; defines and define-syntaxes to be fresh each time.
;; Returns
;; (<identifier> . <binding>)
(define (add-toplevel-binding id)
(cons id
(let ((level (correct-level id)))
(make-binding (if (colours=? (identifier-colours id) no-colours)
(free-name id level)
(generate-name (identifier-name id)))
(list level)))))
;;;=========================================================================
;;;
;;; Syntax-reflect and syntax-reify:
;;;
;;; This is the basic building block of the implicit renaming mechanism for
;;; maintaining hygiene. Syntax-reflect generates the expanded code for
;;; (syntax id), including the expand-time (transformer) environment in the
;;; external representation. It expands to syntax-reify, which performs
;;; the implicit renaming via add-colour when this expanded code is
;;; eventually run.
;;; The level computations perform the adjustment of levels in the presence
;;; of libraries, where meta-levels may be shifted.
;;;
;;;=========================================================================
(define (syntax-reflect id)
`(syntax-reify ',(identifier-name id)
',(identifier-colours id)
;; We reflect the result of capture-transformer-environment
;; even if it is already a reflected environment
;; to ensure that no two reflected identifiers will share
;; an entry in the table of reflected environments.
;; This is essential for consistency given that reflected
;; transformer environments of individual identifiers may
;; be destructively updated during expansion of bodies to make
;; forward references from transformer right hand sides to
;; later definitions work correctly. See scan-body.
',(reflect-env (capture-transformer-env id)
(identifier-colours id))
;; the transformer-expand-time corrected level
,(- (*level*) (identifier-level-correction id) 1)))
(define (syntax-reify name colours transformer-env expand-time-corrected-level)
(make-identifier name
(add-colour (*current-colour*) colours)
(reify-env transformer-env)
;; the transformer-runtime level-correction
(- (*level*) expand-time-corrected-level)))
;;;=====================================================================
;;;
;;; Capture and sexp <-> syntax conversions:
;;;
;;;=====================================================================
(define (datum->syntax tid datum)
(check tid identifier? 'datum->syntax)
(sexp-map (lambda (leaf)
(cond ((const? leaf) leaf)
((symbol? leaf) (make-identifier leaf
(identifier-colours tid)
(identifier-transformer-env tid)
(identifier-level-correction tid)))
(else (syntax-error "Datum->syntax: Invalid datum:" leaf))))
datum))
(define (syntax->datum exp)
(sexp-map (lambda (leaf)
(cond ((const? leaf) leaf)
((identifier? leaf) (identifier-name leaf))
(else
(syntax-error "Syntax->datum: Invalid syntax object:" leaf))))
exp))
;; Fresh identifiers:
(define (generate-temporaries ls)
(check ls list? 'generate-temporaries)
(map (lambda (ignore)
(rename (generate-name 'gen)))
ls))
;; For use internally as in the explicit renaming system.
(define (rename symbol)
(make-identifier symbol
(list (*current-colour*))
(list (cons symbol
(make-binding symbol '(0))))
(*level*)))
;;;=======================================================================
;;;
;;; Colours:
;;;
;;;=======================================================================
;; <colour> ::= <globally unique symbol>
(define (generate-colour)
(generate-name 'col))
(define no-colours '())
(define (add-colour c cs)
(cons c cs))
(define (colours=? c1s c2s)
(equal? c1s c2s))
(define *current-colour* (make-parameter no-colours))
;;;=======================================================================
;;;
;;; Environments:
;;;
;;;=======================================================================
;; An environment is either a reflected
;; environment (a symbol index into a table of environments) or an
;; association list, possibly improper, whose tail may be a reflected
;; environment.
;;
;; <environment> ::= ()
;; | <reflected-env-key>
;; | ((<symbolic-name> . <binding>) . <environment>)
;;
;; <reflected-env-key> ::= <globally unique symbolic key>
;; The table of reflected environments is of the form
;;
;; ((<reflected-env-key> <environment> <colour>) ...)
;; Note: A lot more sharing is possible if object code sizes
;; becomes a problem, but the current implementation seems
;; good enough so far.
(define *reflected-envs* (make-parameter '()))
;; Returns a single-symbol representation of an environment
;; that can be included in object code.
(define (reflect-env env colour)
(let ((key (generate-name 'env)))
(*reflected-envs*
(alist-cons key
(list env
colour)
(*reflected-envs*)))
key))
;; The inverse of the above.
(define (reify-env reflected-env)
(cond ((alist-ref reflected-env (*reflected-envs*))
=> (lambda (probe)
(if (symbol? (car probe))
(reify-env (car probe))
(car probe))))
(else (error "Internal error in reify-env: Environment"
reflected-env
"not in table"
(map car (*reflected-envs*))))))
;; Returns (<name> . <binding>)
(define (env-lookup name env)
(cond ((null? env) #f)
((pair? env)
(if (eq? name (caar env))
(car env)
(env-lookup name (cdr env))))
(else
(env-lookup name (reify-env env)))))
;; Adds new entries to the reflected environment table.
(define (extend-reflected-envs! entries)
(*reflected-envs*
(append entries (*reflected-envs*))))
;; Updates reflected environments of the same
;; colour as id by adding the current usage-env binding of
;; id, which must exist, to them.
;; This is done for all environments created more recently than
;; stop-mark, which points into the table of reflected environments
;; of the above format
;;
;; ((<reflected-env> <transformer-env> <colours>) ...)
;;
;; This is used (see scan-body) to ensure that forward references to
;; this identifier from preceding transformers in a body will
;; work correctly, allowing mutual recursion among
;; transformers as in the even/odd example.
(define (update-reflected-envs! id stop-mark)
(let loop ((start (*reflected-envs*)))
(if (not (eq? start stop-mark))
(let ((entry (cdar start)))
(if (colours=? (identifier-colours id)
(cadr entry))
(set-car! entry
(alist-cons (identifier-name id)
(cdr (lookup-usage-env id))
(car entry))))
(loop (cdr start))))))
;; Returns a mark delimiting the environments currently present
;; in the reflected environment table.
(define (current-reflected-envs-mark)
(*reflected-envs*))
;; Returns only relevant reflected environments for
;; inclusion in object library.
;; This avoids exponentially growing object code when
;; imports are chained.
;;
;; Optimization - If there is only one transformer environment, that
;; represents the initial imports, it means that no
;; additional environments have been reflected. In
;; other words, there are no syntax expressions.
;; Since the initial imports is usually large, it
;; saves a lot of space if we leave it out in this
;; case.
(define (compress-reflected-envs stop-mark)
(let ((result
(let loop ((tenvs (*reflected-envs*))
(entries '()))
(if (eq? tenvs stop-mark)
entries
(loop (cdr tenvs)
(cons (car tenvs)
entries))))))
(if (= 1 (length result))
'()
result)))
;;;=========================================================================
;;;
;;; Transformer environments:
;;;
;;;=========================================================================
;; A transformer environment is an environment of
;; attached to an identifier.
;; Looks up the binding, if any, of an identifier in its
;; attached transformer environment.
;; Returns
;; (<symbolic name> . <binding>) | #f
(define (lookup-transformer-env id)
(env-lookup (identifier-name id)
(identifier-transformer-env id)))
;; Captures the transformer environment of the identifier id by copying
;; like-colored entries from the usage-env valid during expansion
;; of (syntax id). Only like-colored entries are needed to make
;; datum->syntax possible.
;; Optimization: Although not strictly necessary, a big performance gain is
;; achieved by looking up the binding at transformer-expand-time
;; and putting it in front, as we do here. This makes
;; references super-fast.
(define (capture-transformer-env id)
(let* ((rest (append (usage-env->env (identifier-colours id))
(identifier-transformer-env id)))
(first (env-lookup (identifier-name id) rest))) ; +++
(if first ; +++
(cons first rest) ; +++
rest)))
;;;=========================================================================
;;;
;;; Usage environment:
;;;
;;;=========================================================================
;; The usage environment contains the bindings visible
;; during the current expansion step. It gets extended
;; during expansion of binding forms and is used to
;; map <identifier> -> <binding>, where the mapping
;; is keyed via bound-identifier=?, i.e., two identifiers
;; are equivalent for the purpose of the mapping if they
;; have the same symbolic name and colours.
;;
;; It is implemented internally as an alist of the form
;;
;; ((<colours> . <env>) ...)
;;
;; where each <env> is an alist of the form
;;
;; ((<symbolic name> . <binding>) ...)
(define (usage-env->env colours)
(cond ((assoc= colours (*usage-env*) colours=?) => cdr)
(else '())))
;; Lookup-usage-env :: <identifier> -> (<name> . <binding>) | #f
(define (lookup-usage-env id)
(cond ((usage-env->env (identifier-colours id))
=> (lambda (env)
(assq (identifier-name id) env)))
(else #f)))
;; Here <entry> ::= (<id> . <binding>)
;; Returns an extended usage environment built
;; from the current usage-env.
;; Not imperative.
(define (extend-usage-env entry)
(extend-uenv entry (*usage-env*)))
(define (extend-uenv entry uenv)
(let* ((name (identifier-name (car entry)))
(colours (identifier-colours (car entry)))
(binding (cons name (cdr entry))))
(let loop ((uenv uenv))
(cond ((null? uenv)
(list (cons colours
(list binding))))
((colours=? colours (caar uenv))
(cons (cons colours
(cons binding
(cdar uenv)))
(cdr uenv)))
(else
(cons (car uenv)
(loop (cdr uenv))))))))
(define (extend-usage-env* entries)
(let loop ((entries entries)
(uenv (*usage-env*)))
(if (null? entries)
uenv
(loop (cdr entries)
(extend-uenv (car entries) uenv)))))
(define *usage-env* (make-parameter '()))
;;;=========================================================================
;;;
;;; Macros:
;;;
;;;=========================================================================
;; Expanders are system macros that fully expand
;; their arguments to core Scheme, while
;; transformers and variable transformers are
;; user macros.
;; <macro> ::= <expander> | <transformer> | <variable transformer>
(define-struct expander (proc))
(define-struct transformer (proc))
(define-struct variable-transformer (proc))
(define (make-macro proc-or-macro)
(if (procedure? proc-or-macro)
(make-transformer proc-or-macro)
proc-or-macro))
(define *macros* (make-parameter '()))
(define (register-macro! name macro)
(*macros* (extend-macros (cons name macro))))
(define (extend-macros entry)
(cons entry (*macros*)))
(define (extend-macros* entries)
(append entries (*macros*)))
;; Returns <macro> | #f
(define (syntax-use t)
(let ((key (if (pair? t)
(car t)
t)))
(and (identifier? key)
(alist-ref (binding-name key) (*macros*)))))
;;;=========================================================================
;;;
;;; Expander dispatch:
;;;
;;;=========================================================================
;; Transformers are user-defined macros.
;; Expanders are system macros that fully expand
;; their arguments to core Scheme.
(define (expand t)
(stacktrace t
(lambda ()
(cond ((syntax-use t) => (lambda (macro)
(parameterize ((*current-colour* (generate-colour)))
(cond
((expander? macro)
((expander-proc macro) t))
((transformer? macro)
(expand ((transformer-proc macro) t)))
((variable-transformer? macro)
(expand ((variable-transformer-proc macro) t)))
(else
(syntax-error "Internal error: Invalid transformer" macro))))))
((identifier? t) (checked-binding-name t))
((list? t) (map expand t))
((const? t) t)
(else (syntax-error "Invalid syntax object:" t))))))
;; Only expands while t is a user macro invocation.
;; Used by expand-lambda to detect internal definitions.
(define (head-expand t)
(stacktrace t
(lambda ()
(cond
((syntax-use t) => (lambda (macro)
(parameterize ((*current-colour* (generate-colour)))
(cond
((expander? macro) t)
((transformer? macro)
(head-expand ((transformer-proc macro) t)))
((variable-transformer? macro)
(head-expand ((variable-transformer-proc macro) t)))
(else
(syntax-error "Internal error: Invalid transformer" macro))))))
(else t)))))
(define (const? t)
(or (null? t)
(boolean? t)
(number? t)
(string? t)
(char? t)))
;;;=========================================================================
;;;
;;; Quote, if, set!, begin:
;;;
;;;=========================================================================
(define (expand-quote exp)
(or (and (list? exp)
(= (length exp) 2))
(syntax-error))
(syntax->datum exp))
(define (expand-if exp)
(or (and (list? exp)
(<= 3 (length exp) 4))
(syntax-error))
`(if ,(expand (cadr exp))
,(expand (caddr exp))
,@(if (= (length exp) 4)
(list (expand (cadddr exp)))
`())))
(define (expand-set! exp)
(or (and (list? exp)
(= (length exp) 3)
(identifier? (cadr exp)))
(syntax-error))
(cond ((syntax-use (cadr exp)) => (lambda (macro)
(if (variable-transformer? macro)
(expand ((variable-transformer-proc macro) exp))
(syntax-error "Syntax being set! is not a variable transformer."))))
(else `(set! ,(checked-binding-name (cadr exp))
,(expand (caddr exp))))))
(define (expand-begin exp)
(or (list? exp)
(syntax-error))
;; map-in-order is correct for toplevel begin,
;; where syntax definitions affect subsequent
;; expansion.
`(begin ,@(map-in-order expand (cdr exp))))
;;;=========================================================================
;;;
;;; Lambda:
;;;
;;;=========================================================================
;; The expansion algorithm is as in the R6Rs SRFI.
;; Here we expand internal definitions to a specific normalized
;; internal definitions in the host Scheme, but we should
;; probably expand to letrec* for R6RS.
(define (expand-lambda exp)
(if (and (pair? exp)
(pair? (cdr exp))
(formals? (cadr exp))
(list? (cddr exp)))
(let ((formals (cadr exp))
(body (cddr exp)))
(scan-body formals
'()
body
(lambda (formals definitions syntax-definitions declarations ignore-indirects exps)
(if (null? exps)
(syntax-error "Lambda: Empty body."))
(build-primitive-lambda formals definitions exps))))
(syntax-error "Invalid lambda syntax:" exp)))
(define (formals? s)
(or (null? s)
(identifier? s)
(and (pair? s)
(identifier? (car s))
(formals? (cdr s))
(not (dotted-member? (car s)
(cdr s)
bound-identifier=?)))))
;;;=========================================================================
;;;
;;; Bodies: This is used for lambda and library bodies.
;;; May be used for any additional binding forms in host Scheme
;;; that do not expand to lambda or library forms.
;;;
;;;=========================================================================
;; R6RS splicing of internal let-syntax and letrec-syntax (and only
;; this) requires that we control the bindings visible in each
;; expression of the body separately. This is done by attaching
;; any extra bindings that should be visible in the expression
;; (over and above the usual bindings) to the expression.
;; We call the resulting data structure a rib (stealing some
;; vocabulary from psyntax, though the present structure
;; is a bit different from what psyntax has).
(define (make-rib usage-diff macros-diff exp)
(list usage-diff macros-diff exp))
(define rib-usage-diff car)
(define rib-macros-diff cadr)
(define rib-exp caddr)
(define (add-ribs body)
(map (lambda (e)
(make-rib '() '() e))
body))
;; Makes the additional bindings visible and then applies the operation
;; to the expression in the rib. Here the global fluid parameters become
;; a bit inelegant, and I may convert them to ordinary arguments in
;; future.
(define (do-rib operation rb . args)
(parameterize ((*usage-env*
(extend-usage-env* (rib-usage-diff rb)))
(*macros*
(extend-macros* (rib-macros-diff rb))))
(apply operation (rib-exp rb) args)))
;; Copy bindings from rb to expression exp.
(define (copy-rib rb exp)
(make-rib (rib-usage-diff rb)
(rib-macros-diff rb)
exp))
;; Here we expand the first non-definition atomically in case expansion
;; relies on side effects. This is important in a procedural macro
;; system. So that the first non-definition will be expanded correctly,
;; definition-bound identifiers are bound as soon as they are
;; encountered.
;; The continuation k is evaluated in the body environment. This is
;; used example by expand-library to obtain the correct bindings of
;; exported identifiers.
(define (scan-body formals already-bound exps k)
(define (expand-defs defs)
(map (lambda (def)
(cons (car def)
(do-rib expand (cdr def))))
defs))
(define (expand-indirects indirs)
(map (lambda (indir-rib)
(do-rib (lambda (indir)
(map checked-binding-name indir))
indir-rib))
indirs))
(parameterize ((*usage-env*
(extend-usage-env* (map add-local-binding (flatten formals)))))
(let ((formals (dotted-map binding-name formals)))
;; Used below for retroactively updating reflected transformer
;; environments created for expanded syntax expressions in this
;; body, so forward references in syntax forms will work.
(let ((initial-envs-mark (current-reflected-envs-mark)))
(let loop ((rbs (add-ribs exps))
(defs '())
(syntax-defs '())
(decls '())
(indirs '())
(already-bound already-bound))
(if (null? rbs)
(k formals
(expand-defs (reverse defs))
(reverse syntax-defs)
(reverse decls)
(expand-indirects indirs)
'())
(let* ((rb (copy-rib (car rbs) (do-rib head-expand (car rbs))))
(rbs (cdr rbs)))
(cond ((do-rib declare? rb)
(if (and (null? defs)
(null? syntax-defs))
(loop rbs
defs
syntax-defs
(cons (do-rib parse-declaration rb)
decls)
indirs
already-bound)
(syntax-error "Declarations may not follow definitions" exps)))
((do-rib indirect-export? rb)
(loop rbs
defs
syntax-defs
decls
(append (map (lambda (indir)
(copy-rib rb indir))
(do-rib parse-indirect rb))
indirs)
already-bound))
((do-rib define? rb)
(let-values (((id rhs) (do-rib parse-definition rb)))
(if (member=? id already-bound bound-identifier=?)
(syntax-error "Duplicate binding of :" id))
(parameterize ((*usage-env*
(extend-usage-env (add-local-binding id))))
;; Retroactively update reflected transformer environments
;; created for already expanded syntax expressions in
;; preceding syntax definitions in the same body,
;; for identifiers whose colour is the same as id's.
;; The body was started at
;; initial-envs-mark.
;; This is necessary so that forward references to
;; this definition in preceding macros will
;; work correctly, allowing mutual recursion among
;; definitions and macros.
(update-reflected-envs! id
initial-envs-mark)
(loop rbs
(cons (cons (binding-name id) (copy-rib rb rhs))
defs)
syntax-defs
decls
indirs
(cons id already-bound)))))
((do-rib define-syntax? rb)
(let-values (((id rhs) (do-rib parse-definition rb)))
(if (member=? id already-bound bound-identifier=?)
(syntax-error "Duplicate binding of :" id))
(parameterize ((*usage-env*
(extend-usage-env (add-local-binding id))))
;; Retroactively update transformer environments
;; as above.
(update-reflected-envs! id
initial-envs-mark)
(let ((rhs (parameterize ((*level* (+ 1 (*level*))))
(do-rib expand (copy-rib rb rhs)))))
(parameterize ((*macros*
(extend-macros
(cons (binding-name id)
(make-macro (eval rhs))))))
(loop rbs
defs
(cons (cons (binding-name id) rhs)
syntax-defs)
decls
indirs
(cons id already-bound)))))))
((do-rib begin? rb)
(loop (append (map (lambda (exp)
(copy-rib rb exp))
(cdr (rib-exp rb)))
rbs)
defs
syntax-defs
decls
indirs
already-bound))
((do-rib local-syntax? rb)
=> (lambda (type)
(let-values (((formals exps body) (do-rib scan-local-syntax rb)))
(let* ((bindings (map add-local-binding formals))
(usage-diff (append bindings (rib-usage-diff rb)))
(rhs-env (extend-usage-env* usage-diff))
(macros
(map (lambda (exp)
(eval (do-rib (lambda (rb)
(parameterize ((*level* (+ 1 (*level*))))
(case type
((let-syntax) (expand rb))
((letrec-syntax)
(parameterize ((*usage-env* rhs-env))
(expand rb))))))
(copy-rib rb exp))))
exps))
(macros-diff
(append (map (lambda (binding macro)
(cons (binding-symbol (cdr binding))
(make-macro macro)))
bindings
macros)
(rib-macros-diff rb))))
(loop (cons (make-rib usage-diff
macros-diff
`(,(rename 'begin) . ,body))
rbs)
defs
syntax-defs
decls
indirs
already-bound)))))
(else
(k formals
(expand-defs (reverse defs))
(reverse syntax-defs)
(reverse decls)
(expand-indirects indirs)
(cons (do-rib expand rb)
(map (lambda (rb)
(do-rib expand rb))
rbs))))))))))))
(define (make-operator-predicate name)
(let ((p? (make-free-predicate name)))
(lambda (t)
(and (pair? t)
(p? (car t))))))
;; Internal version of free-identifier=?
;; that avoids having to create a special
;; identifier for literal.
(define (make-free-predicate name)
(lambda (t)
(and (identifier? t)
(eq? name (binding-name t)))))
(define declare? (make-operator-predicate 'declare))
(define define? (make-operator-predicate 'define))
(define define-syntax? (make-operator-predicate 'define-syntax))
(define indirect-export? (make-operator-predicate 'indirect-export))
(define begin? (make-operator-predicate 'begin))
(define local-syntax?
(let ((let-syntax? (make-operator-predicate 'let-syntax))
(letrec-syntax? (make-operator-predicate 'letrec-syntax)))
(lambda (t)
(cond ((let-syntax? t) 'let-syntax)
((letrec-syntax? t) 'letrec-syntax)
(else #f)))))
(define (parse-definition t)
(or (and (pair? t)
(pair? (cdr t)))
(syntax-error t))
(let ((k (car t))
(head (cadr t))
(body (cddr t)))
(cond ((and (identifier? head)
(list? body)
(<= (length body) 1))
(values head (if (null? body)
`(,(rename 'unspecified))
(car body))))
((and (pair? head)
(identifier? (car head))
(formals? (cdr head)))
(values (car head)
`(,(rename 'lambda) ,(cdr head) . ,body)))
(else (syntax-error t)))))
(define (parse-declaration t)
(define unsafe? (make-free-predicate 'unsafe))
(define safe? (make-free-predicate 'safe))
(define fast? (make-free-predicate 'fast))
(define small? (make-free-predicate 'small))
(define debug? (make-free-predicate 'debug))
(define (quality? t)
(or (safe? t)
(fast? t)
(small? t)
(debug? t)))
(define (priority? t)
(and (integer? t)
(<= 0 t 3)))
(if (and (list? t)
(= (length t) 2)
(or (unsafe? (cadr t))
(quality? (cadr t))
(and (list? (cadr t))
(= (length t) 2)
(and (quality? (car (cadr t)))
(priority? (cadr (cadr t)))))))
;; Cannot just do syntax->datum.
(if (list? (cadr t))
(cons (checked-binding-name (car (cadr t)))
(cdr (cadr t)))
(checked-binding-name (cadr t)))
(syntax-error t)))
(define (parse-indirect t)
(if (and (list? t)
(andmap (lambda (spec)
(and (list? spec)
(not (null? spec))
(andmap identifier? spec)))
(cdr t)))
(cdr t)
(syntax-error t)))
;;;=========================================================================
;;;
;;; Toplevel let(rec)-syntax:
;;;
;;;=========================================================================
(define (expand-let-syntax t)
(expand-local-syntax t 'let-syntax))
(define (expand-letrec-syntax t)
(expand-local-syntax t 'letrec-syntax))
(define (expand-local-syntax t type)
(let-values (((formals exps body) (scan-local-syntax t)))
(let* ((bindings (map add-local-binding formals))
(new-env (extend-usage-env* bindings))
(procs (map (lambda (exp)
(eval (parameterize ((*level* (+ 1 (*level*))))
(case type
((let-syntax) (expand exp))
((letrec-syntax)
(parameterize ((*usage-env* new-env))
(expand exp)))))))
exps)))
(parameterize ((*usage-env* new-env)
(*macros*
(extend-macros*
(map (lambda (binding macro)
(cons (binding-symbol (cdr binding))
(make-macro macro)))
bindings
procs))))
;; Map-in-order is correct for toplevel local
;; syntax, since splicing occurs and body may
;; contain syntax definitions affecting subsequent
;; expansion.
`(begin ,@(map-in-order expand body))))))
(define (scan-local-syntax t)
(or (and (pair? t)
(pair? (cdr t))
(list? (cadr t))
(list? (cddr t))
(every? (lambda (binding)
(and (pair? binding)
(identifier? (car binding))
(pair? (cdr binding))
(null? (cddr binding))))
(cadr t)))
(syntax-error))
(let ((formals (map car (cadr t)))
(exps (map cadr (cadr t)))
(body (cddr t)))
(or (formals? formals)
(syntax-error))
(values formals
exps
body)))
;;;=========================================================================
;;;
;;; Toplevel definitions:
;;;
;;;=========================================================================
(define (expand-define-syntax t)
(let-values (((id exp) (parse-definition t)))
;; This line makes a difference for macro-generated defines.
(*usage-env* (extend-usage-env (add-toplevel-binding id)))
(register-macro! (binding-name id)
(make-macro (eval (parameterize ((*level* (+ 1 (*level*))))
(expand exp)))))))
(define (expand-define t)
(let-values (((id exp) (parse-definition t)))
;; This line makes a difference for macro-generated defines
(*usage-env* (extend-usage-env (add-toplevel-binding id)))
;; Since expander searches macro table
;; before the usage-env, we have to remove from the
;; former when a toplevel redefinition takes place.
(*macros* (alist-delete (binding-name id)
(*macros*)))
`(define ,(binding-name id)
,(expand exp))))
;;;=========================================================================
;;;
;;; Syntax-case:
;;;
;;;=========================================================================
(define (expand-syntax-case exp)
(if (and (list? exp)
(>= (length exp) 3))
(let ((literals (caddr exp))
(clauses (cdddr exp)))
(if (and (list? literals)
(every? identifier? literals))
(let ((input (generate-name 'input)))
`(let ((,input ,(expand (cadr exp))))
,(process-clauses clauses input literals)))
(syntax-error)))
(syntax-error)))
(define *pattern-env* (make-parameter '()))
(define (process-clauses clauses input literals)
(define (process-match input pattern sk fk)
(cond
((not (symbol? input)) (let ((temp (generate-name 'temp)))
`(let ((,temp ,input))
,(process-match temp pattern sk fk))))
((ellipses? pattern) (syntax-error "Invalid pattern"))
((null? pattern) `(if (null? ,input) ,sk ,fk))
((const? pattern) `(if (equal? ,input ',pattern) ,sk ,fk))
((wildcard? pattern) sk)
((identifier? pattern) (if (member=? pattern literals bound-identifier=?)
`(if (and (identifier? ,input)
(free-identifier=? ,input ,(syntax-reflect pattern)))
,sk
,fk)
`(let ((,(binding-name pattern) ,input)) ,sk)))
((segment-pattern? pattern)
(let ((tail-pattern (cddr pattern)))
(if (null? tail-pattern)
(let ((mapped-pvars (map binding-name (map car (pattern-vars (car pattern) 0)))))
`(if (list? ,input)
,(if (identifier? (car pattern)) ; +++
`(let ((,(binding-name (car pattern)) ,input)) ; +++
,sk) ; +++
`(let ((columns (map-while (lambda (,input)
,(process-match input
(car pattern)
`(list ,@mapped-pvars)
#f))
,input)))
(if columns
(apply (lambda ,mapped-pvars ,sk)
(if (null? columns)
',(map (lambda (ignore) '()) mapped-pvars)
(apply map list columns)))
,fk)))
,fk))
(let ((tail-length (dotted-length tail-pattern)))
`(if (>= (dotted-length ,input) ,tail-length)
,(process-match `(dotted-butlast ,input ,tail-length)
`(,(car pattern) ,(cadr pattern))
(process-match `(dotted-last ,input ,tail-length)
(cddr pattern)
sk
fk)
fk)
,fk)))))
((pair? pattern) `(if (pair? ,input)
,(process-match `(car ,input)
(car pattern)
(process-match `(cdr ,input) (cdr pattern) sk fk)
fk)
,fk))
((vector? pattern) `(if (vector? ,input)
,(process-match `(vector->list ,input)
(vector->list pattern)
sk
fk)
,fk))
(else (syntax-error))))
(define (pattern-vars pattern level)
(cond
((identifier? pattern) (if (or (wildcard? pattern)
(member=? pattern literals bound-identifier=?))
'()
(list (cons pattern level))))
((segment-pattern? pattern) (append (pattern-vars (car pattern) (+ level 1))
(pattern-vars (cddr pattern) level)))
((pair? pattern) (append (pattern-vars (car pattern) level)
(pattern-vars (cdr pattern) level)))
((vector? pattern) (pattern-vars (vector->list pattern) level))
(else '())))
(define (process-clause clause input fk)
(or (and (list? clause)
(>= (length clause) 2))
(syntax-error))
(let* ((pattern (car clause))
(template (cdr clause))
(pvars (pattern-vars pattern 0)))
(or (unique=? (map car pvars) bound-identifier=?)
(syntax-error "Repeated pattern variable in" pattern))
(parameterize ((*pattern-env* (append pvars (*pattern-env*)))
(*usage-env*
(extend-usage-env*
(map add-local-binding (map car pvars)))))
(process-match input
pattern
(cond ((null? (cdr template))
(expand (car template)))
((null? (cddr template))
`(if ,(expand (car template))
,(expand (cadr template))
,fk))
(else (syntax-error)))
fk))))
;; process-clauses
(if (null? clauses)
`(syntax-error ,input)
(let ((fail (generate-name 'fail)))
`(let ((,fail (lambda () ,(process-clauses (cdr clauses) input literals))))
,(process-clause (car clauses) input `(,fail))))))
(define wildcard? (make-free-predicate '_))
;; Ellipsis utilities:
(define ellipses? (make-free-predicate '...))
(define (segment-pattern? pattern)
(and (segment-template? pattern)
(or (andmap (lambda (p)
(not (ellipses? p)))
(flatten (cddr pattern)))
(syntax-error "Invalid segment pattern" pattern))))
(define (segment-template? pattern)
(and (pair? pattern)
(pair? (cdr pattern))
(identifier? (cadr pattern))
(ellipses? (cadr pattern))))
;; Count the number of `...'s in PATTERN.
(define (segment-depth pattern)
(if (segment-template? pattern)
(+ 1 (segment-depth (cdr pattern)))
0))
;; Get whatever is after the `...'s in PATTERN.
(define (segment-tail pattern)
(let loop ((pattern (cdr pattern)))
(if (and (pair? pattern)
(identifier? (car pattern))
(ellipses? (car pattern)))
(loop (cdr pattern))
pattern)))
;; Ellipses-quote:
(define (ellipses-quote? template)
(and (pair? template)
(ellipses? (car template))
(pair? (cdr template))
(null? (cddr template))))
;;;=========================================================================
;;;
;;; Syntax:
;;;
;;;=========================================================================
(define (expand-syntax form)
(or (and (pair? form)
(pair? (cdr form))
(null? (cddr form)))
(syntax-error))
(process-template (cadr form) 0 (*pattern-env*) #f))
(define (process-template template dim env quote-ellipses)
(cond ((and (ellipses? template)
(not quote-ellipses))
(syntax-error "Invalid occurrence of ellipses in syntax template" template))
((identifier? template)
(let ((probe (assoc= template env bound-identifier=?)))
(if probe
(if (<= (cdr probe) dim)
(checked-binding-name template)
(syntax-error "Syntax-case: Template dimension error (too few ...'s?):"
template))
(syntax-reflect template))))
((ellipses-quote? template)
(process-template (cadr template) dim env #t))
((and (segment-template? template)
(not quote-ellipses))
(let* ((depth (segment-depth template))
(seg-dim (+ dim depth))
(vars
(map checked-binding-name
(free-meta-variables (car template) seg-dim env '()))))
(if (null? vars)
(syntax-error "too many ...'s:" template)
(let* ((x (process-template (car template) seg-dim env quote-ellipses))
(gen (if (equal? (list x) vars) ; +++
x ; +++
`(map (lambda ,vars ,x)
,@vars)))
(gen (do ((d depth (- d 1))
(gen gen `(apply append ,gen)))
((= d 1)
gen))))
(if (null? (segment-tail template))
gen ; +++
`(append ,gen ,(process-template (segment-tail template) dim env quote-ellipses)))))))
((pair? template)
`(cons ,(process-template (car template) dim env quote-ellipses)
,(process-template (cdr template) dim env quote-ellipses)))
((vector? template)
`(list->vector ,(process-template (vector->list template) dim env quote-ellipses)))
(else
`(quote ,(expand template)))))
;; Return a list of meta-variables of given higher dim
(define (free-meta-variables template dim env free)
(cond ((identifier? template)
(if (and (not (member=? template free bound-identifier=?))
(let ((probe (assoc= template env bound-identifier=?)))
(and probe (>= (cdr probe) dim))))
(cons template free)
free))
((segment-template? template)
(free-meta-variables (car template) dim env
(free-meta-variables (cddr template) dim env free)))
((pair? template)
(free-meta-variables (car template) dim env
(free-meta-variables (cdr template) dim env free)))
(else free)))
;;;==========================================================================
;;;
;;; Libraries:
;;;
;;; A simple semantics that makes static resolution of imports
;;; possible is to require a single expand-time environment
;;; and simplified rules implying that:
;;;
;;; - each imported library is visited exactly once, and
;;; invoked at most once, during expansion.
;;;
;;; The implementation allows libraries to be imported also at
;;; negative meta-level. However, when there are no negative level
;;; imports in a program, the semantics reduces to the following very
;;; simple rules, which I describe first. The case where negative imports
;;; are allowed is decribed below:
;;;
;;; More precisely, to visit a library in the absence of negative levels:
;;;
;;; * Visit any library that is imported by
;;; this library and that has not yet been visited.
;;; * For each k >= 1, invoke any library that is imported
;;; by this library for .... (meta k), and that has not yet been
;;; invoked.
;;; * Evaluate all syntax definitions in the library.
;;;
;;; To invoke a library in the absence of negative meta levels:
;;;
;;; * Invoke any library that is imported by this library
;;; for run, and that has not yet been invoked.
;;; * Evaluate all variable definitions and expressions in
;;; the library.
;;;
;;; The full semantics implemented here, which is equivalent to the above when there
;;; are no negative levels, is as follows:
;;;
;;; To visit a library at level n:
;;;
;;; * If n < 0 : Do nothing
;;; * If n >= 0 : * Visit at level (n + k) any library that is imported by
;;; this library for (meta k) and that has not yet been visited
;;; for /any/ level.
;;; * For each k >= 1, invoke at level (n + k) any library that is
;;; imported by this library for .... (meta k), and that has not
;;; yet been invoked for /any/ level.
;;; * Evaluate all syntax definitions in the library.
;;;
;;; To invoke a library at level n:
;;;
;;; * If n < 0 : Do nothing.
;;; * If n >= 0 : * Invoke at level (n + k) any library that is imported by this
;;; library for (meta k), and that has not yet been invoked
;;; for /any/ level.
;;; * If n = 0: Evaluate all variable definitions and expressions in
;;; the library.
;;; * If n > 0: Do nothing
;;;
;;; Runtime execution of a library happens in a fresh environment but is
;;; otherwise the same as invoking it.
;;;
;;; This therefore assigns separate environments to each
;;; of the two phases (expansion and execution), and not to each of
;;; the possibly many meta-levels. In each of the two phases, bindings
;;; are shared between whichever levels they are imported into.
;;;
;;;==========================================================================
(define (expand-library t)
(or (and (list? t)
(>= (length t) 4))
(syntax-error "Invalid number of clauses in library spec"))
(let ((keyword (car t))
(name (scan-library-name (cadr t))))
(let-values (((exports) (scan-exports (caddr t)))
((imported-libraries imports) (scan-imports (cadddr t))))
;; Make sure we start with a clean compilation environment,
;; and that we restore any global state afterwards.
;; Make sure macros registered when visiting
;; imported libraries are removed once we are done.
;; We do not restore *visited* and *invoked* in case
;; libraries are redefined.
(*visited* '())
(*invoked* '())
(parameterize ((*reflected-envs* '())
(*usage-env* '())
(*visited* '())
(*invoked* '())
(*macros* (*macros*)))
(visit-imports imported-libraries 0)
;; Obtain a mark so that we know which reflected environments
;; are created for use by this library and should be included
;; in the object code.
(let ((reflected-envs-after-imports (*reflected-envs*)))
;; This step does the actual import by annotating identifiers
;; in the export clause and the body with new transformer environments
;; containing the imported bindings.
(let ((exports-body (reannotate-library (cons exports (cddddr t)) keyword imports)))
(let ((exports (car exports-body))
(body (cdr exports-body)))
(scan-body '()
;; Already-bound list, to enforce no rebinding of imports.
(map (lambda (import)
(datum->syntax keyword (car import)))
imports)
body
(lambda (ignore-formals definitions syntax-definitions declarations indirects exps)
;; This has to be done here, when all bindings are
;; established.
(let* ((exports (map (lambda (entry)
(cons (identifier-name (car entry))
(let ((probe (lookup-binding (cadr entry))))
(if probe
(cdr probe)
(syntax-error "Unbound export" entry)))))
exports))
(all-exports (apply append
(map cadr exports)
;; Also indirectly exported names:
(map (let ((exported-names (map cadr exports)))
(lambda (indir)
(if (memq (car indir) exported-names)
(cdr indir)
'())))
indirects)))
;; This is what we should have to enforce indirect-export,
;; but enforcement has been removed:
;; (exported-def? (lambda (def) (memq (car def) all-exports)))
(exported-def? (lambda (def) #t))
(exported-definitions (filter exported-def? definitions))
(local-definitions (filter (lambda (def)
(not (exported-def? def)))
definitions))
(expanded-library
`(begin
;; Procedure to be invoked when visiting:
;; This is separated from the runtime code
;; below so that it can be left out from the
;; runtime object image if desired.
(define (,(name-for-visit name) message)
(case message
((imported-libraries) ',imported-libraries)
((exports) ',exports)
((visit)
(extend-reflected-envs!
',(compress-reflected-envs reflected-envs-after-imports))
,@(map (lambda (def)
`(register-macro! ',(car def) (make-macro ,(cdr def))))
(filter exported-def? syntax-definitions)))
(else
(error "Invalid operation" message "on library" ',name))))
;; This is the runtime code.
,@(map (lambda (def)
`(define ,(car def) (unspecified)))
exported-definitions)
(define (,(name-for-invoke name) message)
(case message
((imported-libraries) ',imported-libraries)
((invoke)
;; Reproduce letrec* semantics remembering
;; that some of the variables are outside.
,@(map (lambda (def)
`(set! ,(car def) (unspecified)))
exported-definitions)
((lambda ,(map car local-definitions)
,@(map (lambda (def)
`(set! ,(car def) ,(cdr def)))
definitions)
,@(if (null? exps)
`((unspecified))
exps))
,@(map (lambda (ignore) `(unspecified))
local-definitions)))
(else
(error "Invalid operation" message "on library" ',name)))))))
;; Make library available and
;; include in object code:
(eval expanded-library)
expanded-library))))))))))
;; To maintain hygiene with possible macro-generated libraries,
;; we maintain existing colours of identifiers.
;; Only identifiers that have the same colours as the
;; library keyword are bound by imports.
(define (reannotate-library stx keyword imports)
(let ((shared-env
;; Space-optimization - we reflect to ensure
;; tail-sharing of imported bindings, which
;; is typically a large list, in the object
;; library.
;; This sharing is okay for source-level
;; identifiers, since the only reflected
;; environments that can be destructively
;; modified are created during expansion
;; of syntax expressions in trsansformer
;; right hand sides in bodies.
(reflect-env imports (identifier-colours keyword))))
(sexp-map (lambda (leaf)
(cond ((const? leaf) leaf)
((identifier? leaf)
(make-identifier (identifier-name leaf)
(identifier-colours leaf)
(if (colours=? (identifier-colours keyword)
(identifier-colours leaf))
shared-env
'())
(identifier-level-correction leaf)))
(else
(syntax-error "Invalid syntax object:" leaf))))
stx)))
(define *visited* (make-parameter '()))
(define *invoked* (make-parameter '()))
(define (visit-imports imports level)
(if (or (< level 0)
(null? imports))
(unspecified)
(let* ((import (car imports))
(name (car import))
(levels (cdr import)))
(if (null? levels)
(visit-imports (cdr imports) level)
(let* ((level+ (+ level (car levels))))
(if (>= level+ 1)
(invoke name level+))
(visit name level+)
(visit-imports (cons (cons name (cdr levels))
(cdr imports))
level))))))
(define (visit name level)
(if (or (< level 0)
(memq name (*visited*)))
(unspecified)
(let ((imports (eval `(,(name-for-visit name) 'imported-libraries))))
(visit-imports imports level)
(cond ((memq name (*visited*))
(syntax-error "Cyclic library dependency of" name "on" (*visited*)))
(else
(eval `(,(name-for-visit name) 'visit))
(*visited* (cons name (*visited*))))))))
(define (invoke-imports imports level)
(if (or (< level 0)
(null? imports))
(unspecified)
(let* ((import (car imports))
(name (car import))
(levels (cdr import)))
(if (null? levels)
(invoke-imports (cdr imports) level)
(begin
(invoke name (+ level (car levels)))
(invoke-imports (cons (cons name (cdr levels))
(cdr imports))
level))))))
;; TODO - it may be better to compile this into module code, so that
;; invocations of EVAL at runtime are avoided and we simply have
;; ordinary function calls from within the module.
(define (invoke name level)
(if (or (< level 0)
(memq name (*invoked*)))
(unspecified)
(let ((imports (eval `(,(name-for-invoke name) 'imported-libraries))))
(invoke-imports imports level)
(cond ((memq name (*invoked*))
(syntax-error "Cyclic library dependency of" name "on" (*invoked*)))
(else
(eval `(,(name-for-invoke name) 'invoke))
(*invoked* (cons name (*invoked*))))))))
;; Returns ((<rename-identifier> <identifier> <level> ...) ...)
(define (scan-exports clause)
(and (pair? clause)
(export? (car clause))
(list? (cdr clause)))
(let ((exports (apply append
(map scan-export-spec (cdr clause)))))
(or (unique=? exports
(lambda (x y) (eq? (identifier-name (car x))
(identifier-name (car y)))))
(syntax-error "Duplicate export in" clause))
exports))
;; Prior version that had FOR exports:
;;(define (scan-export-spec spec)
;; (let ((levels (scan-levels spec))
;; (export-sets (if (for-spec? spec)
;; (cadr spec)
;; (list spec))))
;; (map (lambda (rename-pair)
;; (cons (car rename-pair)
;; (cons (cdr rename-pair)
;; levels)))
;; (apply append (map scan-export-set export-sets)))))
(define (scan-export-spec spec)
(let ((levels `(0)) ;; Will be ignored in current implementation, but keep data
(export-sets (list spec))) ;; structures and interfaces same in case FOR exports return.
(map (lambda (rename-pair)
(cons (car rename-pair)
(cons (cdr rename-pair)
levels)))
(apply append (map scan-export-set export-sets)))))
(define (scan-export-set set)
(cond ((identifier? set)
(list (cons set set)))
((rename-export-set? set)
(map (lambda (entry)
(cons (cadr entry)
(car entry)))
(cdr set)))
(else
(syntax-error "Invalid export set" set))))
(define (scan-levels spec)
(cond ((for-spec? spec)
(let ((levels
(map (lambda (level)
(cond ((run? level) 0)
((expand? level) 1)
((meta-spec? level) (cadr level))
(else (syntax-error "Invalid level" level "in for spec" spec)))) ;;;;;;; factor
(cddr spec))))
(if (unique=? levels =)
levels
(syntax-error "Repeated level in for spec" spec))))
(else '(0))))
;; Returns (values ((<library name> <level> ...) ....)
;; ((<local name> . <binding>) ...))
;; with no repeats.
(define (scan-imports clause)
(or (and (pair? clause)
(import? (car clause))
(list? (cdr clause)))
(syntax-error "Invalid import clause" clause))
(scan-import-specs (cdr clause)))
(define (scan-import-specs specs)
(let loop ((specs specs)
(imported-libraries '())
(imports '()))
(if (null? specs)
(begin
(or (unique=? imported-libraries
(lambda (x y) (eq? (car x) (car y))))
(syntax-error "Library imported more than once in" imported-libraries))
(values imported-libraries
(unify-imports imports)))
(let-values (((library-name levels more-imports)
(scan-import-spec (car specs))))
(loop (cdr specs)
(if library-name
(cons (cons library-name levels)
imported-libraries)
;; library-name = #f if primitives spec
imported-libraries)
(append more-imports imports))))))
;; Returns (values <library name> | #f
;; (<level> ...)
;; ((<local name> . <binding>) ...)
;; where <level> ::= <uinteger>
;; #f is returned for library name in case of primitives set.
(define (scan-import-spec spec)
(let ((levels (scan-levels spec)))
(let loop ((import-set (if (for-spec? spec)
(cadr spec)
spec))
(renamer (lambda (x) x)))
;; Extension for importing unadorned primitives:
(cond ((primitive-set? import-set)
(values #f
levels
;; renamer will return <symbol> | #f
(filter car
(map (lambda (name)
(cons name
(make-binding name levels)))
(syntax->datum (cadr import-set))))))
((and (list? import-set)
(>= (length import-set) 2)
(or (only-set? import-set)
(except-set? import-set)
(add-prefix-set? import-set)
(rename-set? import-set)))
(loop (cadr import-set)
(compose renamer
;; Remember to correctly propagate if x is #f
(lambda (x)
(cond
((only-set? import-set)
(and (memq x (syntax->datum (cddr import-set)))
x))
((except-set? import-set)
(and (not (memq x (syntax->datum (cddr import-set))))
x))
((add-prefix-set? import-set)
(and x
(string->symbol
(string-append (symbol->string (syntax->datum (caddr import-set)))
(symbol->string x)))))
((rename-set? import-set)
(let ((renames (syntax->datum (cddr import-set))))
(cond ((assq x renames) => cadr)
(else x))))
(else (syntax-error "Invalid import set" import-set)))))))
;; This has to be last or there could be ambiguity
;; if the parentheses shorthand for libraries is allowed.
((library-ref? import-set)
(let* ((library-name (library-ref->symbol import-set))
(exports (eval `(,(name-for-visit library-name) 'exports))))
(let* ((imports
;; renamer will return <symbol> | #f
(filter car
(map (lambda (export)
(cons (renamer (car export))
(make-binding (binding-symbol (cdr export))
(compose-levels levels
(binding-levels (cdr export))))))
exports)))
(all-import-levels (apply unionv
(map (lambda (import)
(binding-levels (cdr import)))
imports))))
(values library-name
levels
imports))))
(else (syntax-error "Invalid import set" import-set))))))
(define (compose-levels levels levels*)
(apply unionv
(map (lambda (level)
(map (lambda (level*)
(+ level level*))
levels*))
levels)))
;; Argument is of the form ((<local name> <binding>) ...)
;; where combinations (<local name> (binding-symbol <binding>)) may be repeated.
;; Return value is of the same format but with no repeats and
;; where union of (binding-levels <binding>)s has been taken for any original repeats.
;; An error is signaled if same <local> occurs with <binding>s
;; whose (binding-symbol <binding>)s are different.
(define (unify-imports imports)
(if (null? imports)
'()
(let* ((first (car imports))
(rest (unify-imports (cdr imports))))
(let loop ((rest rest)
(seen '()))
(cond ((null? rest)
(cons first seen))
((eq? (car first) (caar rest))
(or (eq? (binding-symbol (cdr first))
(binding-symbol (cdar rest)))
(syntax-error "Same name imported from different libraries"
(car first)))
(cons (cons (car first)
(make-binding (binding-symbol (cdr first))
(unionv (binding-levels (cdr first))
(binding-levels (cdar rest)))))
(append seen (cdr rest))))
(else
(loop (cdr rest)
(cons (car rest) seen))))))))
(define (for-spec? spec)
(and (list? spec)
(>= (length spec) 3)
(for? (car spec))))
(define (meta-spec? level)
(and (list? level)
(= (length level) 2)
(meta? (car level))
(integer? (cadr level))))
(define (only-set? set)
(and (only? (car set))
(andmap identifier? (cddr set))))
(define (except-set? set)
(and (except? (car set))
(andmap identifier? (cddr set))))
(define (add-prefix-set? set)
(and (add-prefix? (car set))
(= (length set) 3)
(identifier? (caddr set))))
(define (rename-set? set)
(and (rename? (car set))
(rename-list? (cddr set))))
(define (primitive-set? set)
(and (list? set)
(= (length set) 2)
(primitives? (car set))
(list (cadr set))
(andmap identifier? (cadr set))))
(define (rename-export-set? set)
(and (list? set)
(>= (length set) 1)
(rename? (car set))
(rename-list? (cdr set))))
(define (rename-list? ls)
(andmap (lambda (e)
(and (list? e)
(= (length e) 2)
(andmap identifier? e)))
ls))
(define for? (make-free-predicate 'for))
(define run? (make-free-predicate 'run))
(define expand? (make-free-predicate 'expand))
(define import? (make-free-predicate 'import))
(define export? (make-free-predicate 'export))
(define only? (make-free-predicate 'only))
(define except? (make-free-predicate 'except))
(define add-prefix? (make-free-predicate 'add-prefix))
(define rename? (make-free-predicate 'rename))
(define primitives? (make-free-predicate 'primitives))
(define meta? (make-free-predicate 'meta))
(define (scan-library-name e)
(or (library-name? e)
(syntax-error "Invalid library name" e))
(library-name->symbol e))
(define (library-name? e)
(or (identifier? e)
(and (list? e)
(> (length e) 0)
(identifier? (car e))
(or (andmap (lambda (e)
(and (integer? e) (>= e 0)))
(cdr e))
(library-name? (cdr e))))))
(define (library-name->symbol e)
(if (identifier? e)
(library-name->symbol `(,e))
(make-free-name
(string->symbol
(string-append (symbol->string (syntax->datum (car e)))
(apply string-append
(map (lambda (e)
(string-append "."
(if (identifier? e)
(symbol->string
(syntax->datum e))
(number->string e))))
(cdr e)))))
0)))
;; TODO - predicate references.
(define library-ref? library-name?)
(define library-ref->symbol library-name->symbol)
(define (name-for-visit name)
(string->symbol
(string-append (symbol->string name)
"|visit")))
(define (name-for-invoke name)
(string->symbol
(string-append (symbol->string name)
"|invoke")))
;;;==========================================================================
;;;
;;; Debugging facilities:
;;;
;;;==========================================================================
;; Debugging information displayed by syntax-error.
(define *backtrace* (make-parameter '()))
(define (stacktrace term thunk)
(parameterize ((*backtrace* (cons term (*backtrace*))))
(thunk)))
(define (syntax-warning . args)
(newline)
(display "Syntax warning:")
(display-args args))
(define (syntax-error . args)
(newline)
(display "Syntax error:")
(display-args args)
(for-each (lambda (exp)
(display " ")
(pretty-display (syntax-debug exp))
(newline)
(newline))
(*backtrace*))
(error))
(define (display-args args)
(newline)
(newline)
(for-each (lambda (arg)
(display (syntax-debug arg)) (display " "))
args)
(newline)
(newline))
(define (syntax-debug exp)
(sexp-map (lambda (leaf)
(cond ((identifier? leaf)
(identifier-name leaf))
(else leaf)))
exp))
;;;=====================================================================
;;;
;;; Utilities:
;;;
;;;=====================================================================
(define (flatten l)
(cond ((null? l) l)
((pair? l) (cons (car l)
(flatten (cdr l))))
(else (list l))))
(define (sexp-map f s)
(cond ((null? s) '())
((pair? s) (cons (sexp-map f (car s))
(sexp-map f (cdr s))))
((vector? s)
(apply vector (sexp-map f (vector->list s))))
(else (f s))))
(define (map-in-order f ls)
(if (null? ls)
'()
(let ((first (f (car ls))))
(cons first
(map-in-order f (cdr ls))))))
(define (dotted-member? x ls =)
(cond ((null? ls) #f)
((pair? ls) (or (= x (car ls))
(dotted-member? x (cdr ls) =)))
(else (= x ls))))
(define (dotted-map f lst)
(cond ((null? lst) '())
((pair? lst) (cons (f (car lst))
(dotted-map f (cdr lst))))
(else (f lst))))
;; Returns 0 also for non-list a la SRFI-1 protest.
(define (dotted-length dl)
(cond ((null? dl) 0)
((pair? dl) (+ 1 (dotted-length (cdr dl))))
(else 0)))
(define (dotted-butlast ls n)
(let recurse ((ls ls)
(length-left (dotted-length ls)))
(cond ((< length-left n) (error "Dotted-butlast - list too short" ls n))
((= length-left n) '())
(else
(cons (car ls)
(recurse (cdr ls)
(- length-left 1)))))))
(define (dotted-last ls n)
(let recurse ((ls ls)
(length-left (dotted-length ls)))
(cond ((< length-left n) (error "Dotted-last - list too short" ls n))
((= length-left n) ls)
(else
(recurse (cdr ls)
(- length-left 1))))))
(define (map-while f lst)
(cond ((null? lst) '())
((pair? lst)
(let ((head (f (car lst))))
(if head
(cons head
(map-while f
(cdr lst)))
#f)))
(else '())))
(define (every? p? ls)
(cond ((null? ls) #t)
((pair? ls) (and (p? (car ls))
(every? p? (cdr ls))))
(else #f)))
(define (assoc= key alist =)
(cond ((null? alist) #f)
((= (caar alist) key) (car alist))
(else (assoc= key (cdr alist) =))))
(define (member=? x ls =)
(cond ((null? ls) #f)
((pair? ls) (or (= x (car ls))
(member=? x (cdr ls) =)))
(else (error "Member=?" x ls =))))
(define (unique=? ls =)
(or (null? ls)
(and (not (member=? (car ls) (cdr ls) =))
(unique=? (cdr ls) =))))
(define (filter p? lst)
(if (null? lst)
'()
(if (p? (car lst))
(cons (car lst)
(filter p? (cdr lst)))
(filter p? (cdr lst)))))
(define (unionv . sets)
(cond ((null? sets) '())
((null? (car sets))
(apply unionv (cdr sets)))
(else
(let ((rest (apply unionv
(cdr (car sets))
(cdr sets))))
(if (memv (car (car sets)) rest)
rest
(cons (car (car sets)) rest))))))
(define (alist-cons key datum alist)
(cons (cons key datum) alist))
(define (alist-ref key alist)
(cond ((assq key alist) => cdr)
(else #f)))
(define (alist-delete key alist)
(cond ((null? alist)
'())
((eq? (caar alist) key)
(alist-delete key (cdr alist)))
(else
(cons (car alist)
(alist-delete key (cdr alist))))))
(define (alist-remove-duplicates alist)
(define (rem alist already)
(cond ((null? alist) '())
((memq (caar alist) already) (rem (cdr alist) already))
(else (cons (car alist)
(rem (cdr alist)
(cons (caar alist)
already))))))
(rem alist '()))
(define unspecified
(let ((x (if #f #f)))
(lambda () x)))
(define (compose f g)
(lambda (x) (f (g x))))
(define (check x p? from)
(or (p? x)
(syntax-error from "Invalid argument:" x)))
;;;==========================================================================
;;;
;;; Toplevel:
;;;
;;;==========================================================================
;; Converting source to syntax objects:
(define (source->syntax datum)
(datum->syntax toplevel-template datum))
;; Imports additional bindings into toplevel environment.
;; Syntax is the same as <import spec>.
(define (expand-import t)
(or (and (list? t)
(>= (length t) 1))
(syntax-error))
(import-toplevel (cdr t)))
;; For deterministic toplevel behaviour, we start
;; with clean visited/invoked slate every time.
(define (import-toplevel import-specs)
(let-values (((imported-libraries imports) (scan-import-specs import-specs)))
(visit-imports imported-libraries 0)
(invoke-imports imported-libraries 0)
(*usage-env* (import-usage-env* toplevel-template imports))))
;; Imports at toplevel are done simply by using datum->syntax to create
;; implicit identifiers from the keyword, and mapping these
;; to the external bindings.
(define (import-usage-env* keyword imports)
(extend-usage-env*
(map (lambda (import)
(cons (datum->syntax keyword (car import))
(cdr import)))
imports)))
;;;==========================================================================
;;;
;;; Eval and environment:
;;;
;;;==========================================================================
(define eval-template
(make-identifier 'eval-template
no-colours
'()
0))
(define-struct environment (imported-libraries imports))
(define (environment . import-specs)
(parameterize ((*usage-env* '()))
(parameterize ((*usage-env*
(import-usage-env* eval-template
(map (lambda (name)
(cons name (make-binding name '(0))))
'(for
run
expand
meta
only
except
add-prefix
rename
primitives)))))
(let-values (((imported-libraries imports)
(scan-import-specs
(map (lambda (spec)
(datum->syntax eval-template spec))
import-specs))))
(make-environment imported-libraries imports)))))
(define (r6rs-eval exp env)
(parameterize ((*usage-env* '()))
(let ((exp (reannotate-library (datum->syntax eval-template exp)
eval-template
(environment-imports env))))
(visit-imports (environment-imported-libraries env) 0)
(invoke-imports (environment-imported-libraries env) 0)
(eval (expand exp)))))
;;;==========================================================================
;;;
;;; Toplevel bootstrap:
;;;
;;;==========================================================================
(define toplevel-template
(make-identifier 'toplevel-template
no-colours
'()
0))
;; These are the only bindings available in the initial toplevel
;; environment.
(*usage-env*
(import-usage-env* toplevel-template
(map (lambda (name)
(cons name (make-binding name '(0))))
;; The default language available at toplevel is
;; the syntax import (toplevel meaning)
;; and the R6RS library language:
'(import
library
import
export
for
run
expand
meta
only
except
add-prefix
rename
primitives))))
(*macros* `((library . ,(make-expander expand-library))
(import . ,(make-expander expand-import))
(lambda . ,(make-expander expand-lambda))
(if . ,(make-expander expand-if))
(set! . ,(make-expander expand-set!))
(begin . ,(make-expander expand-begin))
(syntax . ,(make-expander expand-syntax))
(quote . ,(make-expander expand-quote))
(define . ,(make-expander expand-define))
(define-syntax . ,(make-expander expand-define-syntax))
(let-syntax . ,(make-expander expand-let-syntax))
(letrec-syntax . ,(make-expander expand-letrec-syntax))
(syntax-case . ,(make-expander expand-syntax-case))
(_ . ,(make-expander syntax-error))
(... . ,(make-expander syntax-error))
(declare . ,(make-expander syntax-error))
(unsafe . ,(make-expander syntax-error))
(safe . ,(make-expander syntax-error))
(fast . ,(make-expander syntax-error))
(small . ,(make-expander syntax-error))
(debug . ,(make-expander syntax-error))
;; (indirect-export . ,(make-expander syntax-error)) - removed
(for . ,(make-expander syntax-error))
(run . ,(make-expander syntax-error))
(expand . ,(make-expander syntax-error))
(meta . ,(make-expander syntax-error))
(only . ,(make-expander syntax-error))
(except . ,(make-expander syntax-error))
(add-prefix . ,(make-expander syntax-error))
(rename . ,(make-expander syntax-error))
(primitives . ,(make-expander syntax-error))))
;;;============================================================================
;;;
;;; REPL integration:
;;;
;;;============================================================================
(define (repl exps)
(for-each (lambda (exp)
;; This is only necessary to reprise
;; in case of error:
(reset-toplevel!)
(for-each (lambda (result)
(display result)
(newline))
(call-with-values
(lambda ()
(eval (expand (source->syntax exp))))
list)))
exps))
(define (reset-toplevel!)
(*backtrace* '())
(*pattern-env* '())
(*level* 0)
(*current-colour* no-colours))
;;;==========================================================================
;;;
;;; Load and expand-file:
;;;
;;;==========================================================================
;; This may be used as a front end for the compiler:
(define (expand-file filename)
(reset-toplevel!)
(map-in-order expand (map source->syntax (read-file filename))))
(define (r6rs-load filename)
(for-each eval (expand-file filename)))
(define read-file
(lambda (fn)
(let ((p (open-input-file fn)))
(let f ((x (read p)))
(if (eof-object? x)
(begin (close-input-port p) '())
(cons x
(f (read p))))))))
;;;==========================================================================
;;;
;;; Make derived syntaxes available:
;;;
;;;==========================================================================
;; This expands and loads the core libraries composing r6rs.
;; In production, instead of doing this, just include the result
;; of compiling (expand-file "macros-derived.scm")
(r6rs-load "macros-derived.scm")
| true |
169e7a11c86b964a9eccdfa556394485aeb461db
|
de5d387aa834f85a1df3bd47bc324b01130f21fb
|
/ps5/code/pattern-directed-invocation.scm
|
193d38bd930eb3a173e247120f79f6fe9dd04eaf
|
[] |
no_license
|
chuchao333/6.945
|
5ae15980a952bed5c868be03d1a71b1878ddd53d
|
c50bb28aadf0c3fcda3c8e56b4a61b9a2d582552
|
refs/heads/master
| 2020-05-30T20:23:23.501175 | 2013-05-05T19:59:53 | 2013-05-05T19:59:53 | 24,237,118 | 5 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,005 |
scm
|
pattern-directed-invocation.scm
|
(declare (usual-integrations))
(define (make-rule pattern handler)
(if (user-handler? handler)
(make-rule pattern (user-handler->system-handler handler))
(let ((pattern-combinator (->combinators pattern)))
(lambda (data #!optional succeed fail)
(if (default-object? succeed)
(set! succeed (lambda (value fail) value)))
(if (default-object? fail)
(set! fail (lambda () #f)))
(pattern-combinator data
(lambda (dict fail)
(handler dict succeed fail))
fail)))))
(define (make-pattern-operator #!optional rules)
(define (operator self . arguments)
(define (succeed value fail) value)
(define (fail)
(error "No applicable operations" self arguments))
(try-rules arguments (entity-extra self) succeed fail))
(make-entity operator (if (default-object? rules) '() rules)))
(define (attach-rule! operator rule)
(set-entity-extra! operator
(cons rule (entity-extra operator))))
(define (rule-simplifier the-rules)
(define (simplify-expression expression)
(let ((subexpressions-simplified
(if (list? expression)
(map simplify-expression expression)
expression)))
(try-rules subexpressions-simplified the-rules
(lambda (result fail)
(simplify-expression result))
(lambda ()
subexpressions-simplified))))
(rule-memoize simplify-expression))
(define (try-rules data rules succeed fail)
(let per-rule ((rules rules))
(if (null? rules)
(fail)
((car rules) data succeed
(lambda ()
(per-rule (cdr rules)))))))
;;; The user-handler is expected to be a procedure that binds the
;;; variables that appear in the match and uses them somehow. This
;;; converts it into a combinator that accepts the match dictionary,
;;; and success and failure continuations. Does not deal with
;;; optional and rest arguments in the handler.
(define (user-handler->system-handler user-handler)
(let ((handler-argl (procedure-argl user-handler)))
(system-handler!
(lambda (dict succeed fail)
(define (matched-value name)
(match:value
(or (match:lookup name dict)
(error "Handler asked for unknown name"
name dict))))
(let* ((argument-list (map matched-value handler-argl))
(user-answer (apply user-handler argument-list)))
(if user-answer
(succeed user-answer fail)
(fail)))))))
(define (user-handler? thing)
(not (system-handler? thing)))
(define (system-handler? thing)
(eq-get thing 'system-handler))
(define (system-handler! thing)
(eq-put! thing 'system-handler #t)
thing)
(define (->combinators pattern)
(let ((class-combinator
(match:->combinators pattern)))
(lambda (data succeed fail)
(or (class-combinator data '()
(lambda (value)
(succeed value (lambda () #f))))
(fail)))))
(define-syntax rule
(sc-macro-transformer
(lambda (form use-env)
(let ((pattern (cadr form))
(handler-body (caddr form)))
`(make-rule
,(close-syntax pattern use-env)
,(compile-handler handler-body use-env
(match:pattern-names pattern)))))))
(define (compile-handler form env names)
;; See magic in utils.scm
(make-lambda names env
(lambda (env*) (close-syntax form env*))))
#|
(pp (syntax '(rule '(* (? a) (? b))
(and (expr<? a b)
`(* ,a ,b)))
(the-environment)))
; (make-rule '(* (? a) (? b))
; (lambda (b a)
; (and (expr<? a b)
; (list '* a b))))
;Unspecified return value
|#
;;; Pattern-directed factorial, with and without the rule macro.
#|
(define factorial (make-pattern-operator))
(attach-rule! factorial (rule '(0) 1))
(attach-rule! factorial
(rule `((? n ,positive?))
(* n (factorial (- n 1)))))
(factorial 10)
;Value: 3628800
|#
#|
(define factorial (make-pattern-operator))
(attach-rule! factorial
(make-rule '((? n))
(lambda (n) (* n (factorial (- n 1))))))
(attach-rule! factorial
(make-rule '(0) (lambda () 1)))
(factorial 10)
;Value: 3628800
|#
| true |
91af41c7b97c14b6d569a03f550bea90057db9e9
|
434a6f6b2e788eae6f6609d02262f9c9819773a7
|
/day08/program-a.scm
|
8bb35c8b5b1cca410129c2f5012250ef4da70350
|
[] |
no_license
|
jakeleporte/advent-of-code-2020
|
978fc575d580c63386c53bb40fc14f24d5137be7
|
649292bf17feaccf572e02d4dad711d2c46d66cb
|
refs/heads/main
| 2023-02-07T22:29:08.479708 | 2021-01-03T01:16:22 | 2021-01-03T01:16:22 | 318,069,993 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,067 |
scm
|
program-a.scm
|
#!/usr/bin/env guile
!#
(use-modules (ice-9 rdelim) (ice-9 receive) (ice-9 match))
(define (read-code)
"Read code and return vector of (op . arg) pairs"
(let loop ((line (read-line)) (code '()))
(if (eof-object? line)
(list->vector code)
(let* ((inst (string-tokenize line))
(op (car inst))
(arg (string->number (cadr inst))))
(loop (read-line)
(append code (list (cons op arg))))))))
(define (find-loop code)
"Runs the input code until a loop is found
and returns the value of the accumulator"
(define visited (make-hash-table (vector-length code)))
(let loop ((pc 0) (acc 0))
;; If this instruction has already been visited,
;; return the accumulator value
(if (hash-ref visited pc) acc
(begin (hash-set! visited pc #t)
(receive (op arg) (values (car (vector-ref code pc))
(cdr (vector-ref code pc)))
(match op
("nop" (loop (1+ pc) acc))
("acc" (loop (1+ pc) (+ acc arg)))
("jmp" (loop (+ pc arg) acc))))))))
(define (main)
(display (find-loop (read-code))) (newline))
(main)
| false |
a9aa598117d875f45a1f7cb15ece87f509cc2916
|
81788f723d53fa098f2fce87d4d022dc78aaa68c
|
/chap-4/jp-leval.scm
|
b8a5a5c68e6812e6c2f229885e693901976a3ab8
|
[] |
no_license
|
docmatrix/sicp
|
01ef2028b1fde0c035e4fa49106d2e07b4baf42d
|
c7f1214bdd6da23ef8edb0670b61cdb222147674
|
refs/heads/master
| 2020-12-24T06:44:10.783386 | 2017-11-28T17:03:09 | 2017-11-28T17:03:09 | 58,923,881 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,041 |
scm
|
jp-leval.scm
|
(load "support/ch4-leval.scm")
(use-modules (syntax-table))
(define (eval exp env)
(cond ((self-evaluating? exp) exp)
((variable? exp) (lookup-variable-value exp env))
((pair? exp)
(let ((installed-eval (get-syntax (operator exp))))
(if installed-eval
(installed-eval exp env)
(apply-jp (actual-value (operator exp) env) (operands exp) env))))
(else
(error "Unknown expression
type: EVAL" exp))))
(put-syntax! 'quote (lambda (exp env) (text-of-quotation exp)))
(put-syntax! 'set! (lambda (exp env) (eval-assignment exp env)))
(put-syntax! 'define (lambda (exp env) (eval-definition exp env)))
(put-syntax! 'lambda (lambda (exp env) (make-procedure (lambda-parameters exp) (lambda-body exp) env)))
(put-syntax! 'begin (lambda (exp env) (eval-sequence (begin-actions exp) env)))
(put-syntax! 'if (lambda (exp env) (eval-if exp env)))
(put-syntax! 'cond (lambda (exp env)(eval (cond->if exp) env)))
(load "tests-leval.scm")
(run-tests)
| false |
8df1477c6bace2a699733633217512bf843db9c7
|
05ceb7bd2213fea402c2c563aa45f149aae2b049
|
/3rdparty/sndlib/noise.scm
|
12ced3cfd000186f2b55bca87e84e98b54f68179
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
alexanderlerch/libACA
|
f114bd5d06ce36fa76083bded281364055b50d65
|
1b81f65a6d2a129fb43b8aa487df0645eb146f23
|
refs/heads/main
| 2023-05-23T01:09:46.110481 | 2022-09-12T18:38:02 | 2022-09-12T18:38:02 | 485,183,471 | 51 | 4 |
MIT
| 2022-06-17T19:18:47 | 2022-04-25T01:20:38 |
C++
|
UTF-8
|
Scheme
| false | false | 7,738 |
scm
|
noise.scm
|
;;; noise.scm -- CLM -> Snd/Scheme translation of noise.ins
;; Translator/Author: Michael Scholz <[email protected]>
;; Last: Wed Apr 02 02:47:21 CEST 2003
;; Version: $Revision: 1.9 $
;;; Comments not otherwise noted are taken from noise.ins!
;; Included functions:
;; (attack-point duration attack decay (total-x 100.0))
;; (fm-noise ...)
;; (make-fm-noise len freq ...)
;;; The "noise" instrument (useful for Oceanic Music):
(provide 'snd-noise.scm)
(if (not (provided? 'snd-ws.scm)) (load "ws.scm"))
(if (not (provided? 'snd-env.scm)) (load "env.scm"))
(define *locsig-type* mus-interp-sinusoidal)
(define* (attack-point duration attack decay (total-x 100.0))
(* total-x (/ (if (= 0.0 attack)
(if (= 0.0 decay)
(/ duration 4)
(/ (- duration decay) 4))
attack)
duration)))
(definstrument (fm-noise startime dur freq0 amp ampfun ampat ampdc
freq1 glissfun freqat freqdc rfreq0 rfreq1 rfreqfun rfreqat rfreqdc
dev0 dev1 devfun devat devdc
(degree 0.0)
(distance 1.0)
(reverb-amount 0.005))
;; ampat = amp envelope attack time, and so on -- this instrument
;; assumes your envelopes go from 0 to 100 on the x-axis, and that
;; the "attack" portion ends at 25, the "decay" portion starts at
;; 75. "rfreq" is the frequency of the random number generator --
;; if below about 25 hz you get automatic composition, above that
;; you start to get noise. well, you get a different kind of noise.
;; "dev" is the bandwidth of the noise -- very narrow gives a
;; whistle, very broad more of a whoosh. this is basically "simple
;; fm", but the modulating signal is white noise.
(let (;; fix-up troubles in attack and decay times (there are
;; lots of ways to handle this -- the basic problem is that
;; these durned instruments end up having way too many
;; parameters. rick taube's common music replacement for pla
;; should help, but just for old time's sake, we'll do it the
;; way the ancients did it. (we could also package up this
;; stuff in our own function, somewhat like the allvln
;; function in vln.clm, leaving the instrument code to apply
;; envelopes and other data to some patch).
(amp-attack (attack-point dur ampat ampdc))
(amp-decay (- 100.0 (attack-point dur ampdc ampat)))
(freq-attack (attack-point dur freqat freqdc))
(freq-decay (- 100.0 (attack-point dur freqdc freqat)))
(dev-attack (attack-point dur devat devdc))
(dev-decay (- 100.0 (attack-point dur devdc devat)))
(rfreq-attack (attack-point dur rfreqat rfreqdc))
(rfreq-decay (- 100.0 (attack-point dur rfreqdc rfreqat))))
(let ((beg (seconds->samples startime))
(end (seconds->samples (+ startime dur)))
(carrier (make-oscil freq0))
(modulator (make-rand :frequency rfreq0 :amplitude 1.0))
(loc (make-locsig :degree degree
:distance distance
:reverb reverb-amount
:type *locsig-type*))
;; now make the actual envelopes -- these all assume we are
;; thinking in terms of the "value when the envelope is 1"
;; (i.e. dev1 and friends), and the "value when the envelope
;; is 0" (i.e. dev0 and friends) -- over the years this
;; seemed to make beginners happier than various other ways
;; of describing the y-axis behaviour of the envelope. all
;; this boiler-plate for envelopes might seem overly
;; elaborate when our basic instrument is really simple, but
;; in most cases, and this one in particular, nearly all the
;; musical interest comes from the envelopes, not the
;; somewhat dull spectrum generated by the basic patch.
(dev-f (make-env (stretch-envelope devfun 25 dev-attack 75 dev-decay)
:duration dur
:offset (hz->radians dev0)
:scaler (hz->radians (- dev1 dev0))))
(amp-f (make-env (stretch-envelope ampfun 25 amp-attack 75 amp-decay)
:duration dur :scaler amp))
(freq-f (make-env (stretch-envelope glissfun 25 freq-attack 75 freq-decay)
:duration dur :scaler (hz->radians (- freq1 freq0))))
(rfreq-f (make-env (stretch-envelope rfreqfun 25 rfreq-attack 75 rfreq-decay)
:duration dur :scaler (hz->radians (- rfreq1 rfreq0)))))
(do ((i beg (+ i 1)))
((= i end))
(locsig loc i (* (env amp-f)
(oscil carrier (+ (env freq-f)
(* (env dev-f) (rand modulator (env rfreq-f)))))))))))
;;; (with-sound () (fm-noise 0 0.5 500 0.25 '(0 0 25 1 75 1 100 0) 0.1 0.1 1000 '(0 0 100 1) 0.1 0.1 10 1000 '(0 0 100 1) 0 0 100 500 '(0 0 100 1) 0 0))
;; (let* ((ofile "test.snd")
;; (snd (find-sound ofile)))
;; (if snd
;; (close-sound snd))
;; (with-sound (:output ofile :play 1 :statistics #t)
;; (fm-noise 0 2.0 500 0.25 '(0 0 25 1 75 1 100 0) 0.1 0.1
;; 1000 '(0 0 100 1) 0.1 0.1
;; 10 1000 '(0 0 100 1) 0 0
;; 100 500 '(0 0 100 1) 0 0)))
;;; And here is a generator-like instrument, see make-fm-violin in
;;; fmv.scm. [MS]
(define* (make-fm-noise len freq
(amp 0.25)
(ampfun '(0 0 25 1 75 1 100 0))
(ampat 0.1)
(ampdc 0.1)
(freq1 1000)
(glissfun '(0 0 100 1))
(freqat 0.1)
(freqdc 0.1)
(rfreq0 10)
(rfreq1 1000)
(rfreqfun '(0 0 100 1))
(rfreqat 0)
(rfreqdc 0)
(dev0 100)
(dev1 500)
(devfun '(0 0 100 1))
(devat 0)
(devdc 0)
(degree (random 90.0))
(distance 1.0)
(reverb-amount 0.005))
(let* ((dur (/ len (floor (srate))))
(amp-attack (attack-point dur ampat ampdc))
(amp-decay (- 100.0 (attack-point dur ampdc ampat)))
(freq-attack (attack-point dur freqat freqdc))
(freq-decay (- 100.0 (attack-point dur freqdc freqat)))
(dev-attack (attack-point dur devat devdc))
(dev-decay (- 100.0 (attack-point dur devdc devat)))
(rfreq-attack (attack-point dur rfreqat rfreqdc))
(rfreq-decay (- 100.0 (attack-point dur rfreqdc rfreqat)))
(dev-ff (make-env (stretch-envelope devfun 25 dev-attack 75 dev-decay)
:duration dur :scaler (hz->radians (- dev1 dev0))))
(amp-ff (make-env (stretch-envelope ampfun 25 amp-attack 75 amp-decay)
:duration dur :scaler amp))
(freq-ff (make-env (stretch-envelope glissfun 25 freq-attack 75 freq-decay)
:duration dur :scaler (hz->radians (- freq1 freq))))
(rfreq-ff (make-env (stretch-envelope rfreqfun 25 rfreq-attack 75 rfreq-decay)
:duration dur :scaler (hz->radians (- rfreq1 rfreq0))))
(carrier (make-oscil freq))
(modulator (make-rand :frequency rfreq0 :amplitude 1.0))
(dev-0 (hz->radians dev0))
(dev-f (lambda () (env dev-ff)))
(amp-f (lambda () (env amp-ff)))
(freq-f (lambda () (env freq-ff)))
(rfreq-f (lambda () (env rfreq-ff))))
(lambda ()
(* (amp-f) (oscil carrier (+ (freq-f) (* (+ dev-0 (dev-f)) (rand modulator (rfreq-f)))))))))
;; (let* ((beg 0)
;; (dur 9.8)
;; (len (+ beg (floor (* dur (srate)))))
;; (chns 4)
;; (outfile "test.snd")
;; (snd (find-sound outfile))
;; (loc (make-locsig :degree (random 3535.0) :channels chns))
;; (data (make-vct len)))
;; (do ((i 0 (+ i 1)))
;; ((= i len))
;; (set! (data i) (make-fm-noise len 500)))
;; (if snd
;; (close-sound snd))
;; (set! snd (new-sound outfile mus-next mus-bshort (mus-srate) chns))
;; (do ((i 0 (+ i 1)))
;; ((= i chns))
;; (mix-vct (vct-scale! (vct-copy data) (locsig-ref loc i)) beg snd i #f))
;; (let* ((beg (floor (* 10 (srate))))
;; (len (+ beg (floor (* dur (srate)))))
;; (loc (make-locsig :degree (random 3535.0) :channels chns))
;; (data (make-vct len)))
;; (do ((i 0 (+ i 1)))
;; ((= i len))
;; (set! (data i) (make-fm-noise len 200)))
;; (do ((i 0 (+ i 1)))
;; ((= i chns))
;; (mix-vct (vct-scale! (vct-copy data) (locsig-ref loc i)) beg snd i #f))
;; (play snd 0)))
;; noise.scm ends here
| false |
e7b0c1c7a80b0c57e3e944739645dfb0338bb6ab
|
6b5618fe9412ac9c1fb94a24a2e4ebd1838a763d
|
/wak/testeez/scheme/run.scm
|
41b45f99e2949dc4eee76898f32debdceca7bdd4
|
[] |
no_license
|
okuoku/htmlparse
|
d959f9589b8d04d1f09400eb3df153324608f68e
|
e2e88932b1bdc5e2254dd4a66026b6f3a81a803e
|
refs/heads/master
| 2021-01-15T11:48:17.368503 | 2011-08-12T20:20:02 | 2011-08-12T20:20:02 | 2,200,602 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 7,261 |
scm
|
run.scm
|
;; run.scm -- test drivers
;; Copyright (C) 2004, 2005, 2006-2008 by Free Software Foundation, Inc.
;; Author: Jose Antonio Ortega Ruiz <[email protected]>
;; Start date: Thu Nov 04, 2004 13:24
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU Lesser General Public License as published by
;; the Free Software Foundation; either version 2.1 of the License, or
;; (at your option) any later version.
;;
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
;;; Comentary:
;; Utilities to lauch tests written using infrastructure.scm
;;; Code:
;;@ Run specified tests. The first argument is a list whose
;; elements can be either directories or single file names:
;; @code{run-tests-in-directory} or @code{run-tests-in-file} is
;; applied accordingly. If empty is provided, the current directory is
;; used. The second argument is an identifier of the scheme dialect in
;; use, which can appear in the @code{only-dialects} and
;; @code{all-dialects-except} marker forms in test files.
(define (run-tests tests dialect env)
(for-each (lambda (f)
(cond ((file-directory? f) (run-tests-in-directory f dialect env))
((file-regular? f) (run-tests-in-file f dialect env))
(else
(display (list "skipping non-existing" f))
(newline))))
tests))
(define (run-tests-and-exit tests dialect env)
(run-tests tests dialect env)
(exit 0))
;;@ Call @code{run-tests-in-file} for each file in the given
;; directory. If the directory contains a file named @file{tests.scm},
;; the list of files is read from it.
(define (run-tests-in-directory dir dialect env)
(let ((listing (make-pathname #f dir (make-file "tests" "scm"))))
(let ((files (if (file-regular? listing)
(map (lambda (x)
(pathname-with-file dir (cond ((string? x) x)
(else (car x)))))
(with-input-from-file (x->namestring listing) read))
(directory-fold dir cons '()))))
(for-each (lambda (f)
(run-tests-in-file f dialect env))
files))))
;;@ Load the given file if it contains at least one
;; @code{testeez} form. @code{dialect} is used to skip, if necessary,
;; test files containing @code{only-dialects} or
;; @code{all-dialects-except} forms.
(define run-tests-in-file
(letrec ((find
(lambda (l)
(cond
((not (pair? l)) #f)
((pair? (car l)) (or (find (car l)) (find (cdr l))))
(else (or (eq? 'testeez (car l)) (find (cdr l)))))))
(cont?
(lambda (l d)
(cond ((eof-object? l) #f)
((not (pair? l)) #t)
((eq? (car l) 'only-dialects) (memq d (cdr l)))
((eq? (car l) 'all-dialects-except) (not (memq d (cdr l))))
(else #t)))))
(lambda (file dialect env)
(newline)
(let ((filename (x->namestring file)))
(with-input-from-file filename
(lambda ()
(let loop ((in (read)))
(cond ((find in)
(begin (display (list "Loading " filename "... "))
(newline)
(call-with-input-file filename
(lambda (port)
(let loop ((forms '()))
(let ((form (read port)))
(if (eof-object? form)
(eval `(let () ,@(reverse forms)) env)
(loop (cons form forms)))))))
(display (list "..." filename "done"))
(newline)))
((cont? in dialect) (loop (read)))))))))))
(define package-name->import-spec
(let ((all-but-dot (char-set-complement (char-set #\.))))
(lambda (spec)
(if (symbol? spec)
(map string->symbol (string-tokenize (symbol->string spec) all-but-dot))
spec))))
(define (construct-test-environment imports)
(guard (c (#t (display "(Error constructing environment: ")
(newline)
(for-each (lambda (line)
(display line)
(newline))
(format-exception c))
(display ")")
(newline)
#f))
(apply environment
(append
'((except (rnrs base) error string-copy string-for-each string->list)
(rnrs io simple)
(testeez)
(testeez run-env))
imports))))
;; test spec grammar:
;;
;; <test spec> -> (<clause> ...)
;; <clause> -> (systems <system name> ...)
;; (files (<file spec> <required library>) ...)
;; <code> -> <filename>
;; (code <scheme expr> ...) <filename>
(define (eval-test-spec dialect pathname test-spec tests)
(for-each
(lambda (spec)
(case (car spec)
((systems)
(for-each (lambda (system) ((system-loader) system)) (cdr spec)))
((files)
(for-each
(lambda (clause)
(cond ((or (null? tests) (member (car clause) tests))
(let* ((head (car clause))
(code-there? (and (list? head) (eq? 'code (car head))))
(code (if code-there? (cdr head) '()))
(fpath (if code-there? (cadr clause) head))
(pkgs (map package-name->import-spec ((if code-there? cddr cdr) clause)))
(env (construct-test-environment pkgs)))
(when env
(parameterize ((test-environment env))
(guard (c (#t (display (list "Uncaught exception during tests: " c))
(newline)))
(unless (null? code)
(eval `(let () ,@code) env))
(run-tests
(list (pathname-with-file pathname fpath))
dialect
env))))))))
(cdr spec)))))
test-spec))
(define (main args)
(for-each (lambda (tests-file)
(call-with-input-file tests-file
(lambda (port)
(let ((test-spec (read port))
(pathname (x->pathname tests-file)))
(parameterize
((this-directory (directory-namestring pathname)))
(eval-test-spec (scheme-dialect) pathname test-spec '()))))))
(cdr args)))
;;; run.scm ends here
| false |
4a3da49ae464fb93f405a000914d74ef299098a0
|
961ccc58c2ed4ed1d84a78614bedf0d57a2f2174
|
/scheme/chapter2/nqueens.scm
|
b8f26f09af537e3a8aefb5c86000fc527be6f178
|
[] |
no_license
|
huangjs/mostly-lisp-code
|
96483b566b8fa72ab0b73bf0e21f48cdb80dab0d
|
9fe862dbb64f2a28be62bb1bd996238de018f549
|
refs/heads/master
| 2021-01-10T10:11:50.121705 | 2015-11-01T08:53:22 | 2015-11-01T08:53:22 | 45,328,850 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,802 |
scm
|
nqueens.scm
|
(define (filter predicate items)
(cond ((null? items) '())
((predicate (car items))
(cons (car items)
(filter predicate (cdr items))))
(else (filter predicate (cdr items)))))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (append seq1 seq2)
(accumulate cons seq2 seq1))
(define (flatmap proc seq)
(accumulate append '() (map proc seq)))
(define (enumerate-interval low high)
(if (> low high)
'()
(cons low (enumerate-interval (+ 1 low) high))))
(define (queens board-size)
(define (queen-cols k)
(if (= k 0)
(list empty-board)
(filter
(lambda (positions) (safe? k positions))
(flatmap
(lambda (rest-of-queens)
(map (lambda (new-row)
(adjoin-position new-row k rest-of-queens))
(enumerate-interval 1 board-size)))
(queen-cols (- k 1))))))
(queen-cols board-size))
(define (adjoin-position r k rest-of-queens)
(cons (list r k) rest-of-queens))
(define empty-board '())
(define (safe? k positions)
(define (same-line? p1 p2)
(let ((r1 (car p1))
(k1 (cadr p1))
(r2 (car p2))
(k2 (cadr p2)))
(or (= r1 r2)
(= (+ r1 k1)
(+ r2 k2))
(= (- r1 k1)
(- r2 k2)))))
(define (safe-simple? p1 p2)
(not (same-line? p1 p2)))
(let ((test-pos (car positions))
(rest-pos (cdr positions)))
(accumulate (lambda (a b)
(and a b))
#t
(map (lambda (p)
(safe-simple? p test-pos))
rest-pos))))
;(display (queens 8))
;(newline)
| false |
c92c836b0b0cd54e078b5e982b4affaa26f33711
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/io/search-pattern.sls
|
a0f2b0876fcfe1b9ad528cdbaac3ddcdf8a911d2
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 473 |
sls
|
search-pattern.sls
|
(library (system io search-pattern)
(export new is? search-pattern? is-match?)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new System.IO.SearchPattern a ...)))))
(define (is? a) (clr-is System.IO.SearchPattern a))
(define (search-pattern? a) (clr-is System.IO.SearchPattern a))
(define-method-port
is-match?
System.IO.SearchPattern
IsMatch
(System.Boolean System.String)))
| true |
75bf1e1132e9009a078bb5ce000991a2180b28a1
|
5355071004ad420028a218457c14cb8f7aa52fe4
|
/3.3/e-3.25.scm
|
84f2fe753ce03e97524ea77be12a624d1140ae28
|
[] |
no_license
|
ivanjovanovic/sicp
|
edc8f114f9269a13298a76a544219d0188e3ad43
|
2694f5666c6a47300dadece631a9a21e6bc57496
|
refs/heads/master
| 2022-02-13T22:38:38.595205 | 2022-02-11T22:11:18 | 2022-02-11T22:11:18 | 2,471,121 | 376 | 90 | null | 2022-02-11T22:11:19 | 2011-09-27T22:11:25 |
Scheme
|
UTF-8
|
Scheme
| false | false | 2,682 |
scm
|
e-3.25.scm
|
; Exercise 3.25.
;
; Generalizing one- and two-dimensional tables, show how to
; implement a table in which values are stored under an arbitrary number of
; keys and different values may be stored under different numbers of keys. The
; lookup and insert! procedures should take as input a list of keys used to
; access the table.
; ------------------------------------------------------------
(load "../helpers.scm")
; This is not hard to do only if we allow hierarchical data structure where
; value of the key/value pair to be new 1D table.
(define (make-table)
(define (assoc key records)
(cond ((null? records) '#f)
((equal? key (caar records)) (car records))
(else (assoc key (cdr records)))))
(let ((local-table (list '*table*)))
(define (lookup keys)
(define (lookup-recursive keys table)
(let ((record (assoc (car keys) (cdr table))))
(if record
(if (null? (cdr keys))
(cdr record)
(if (pair? (cdr record))
(lookup-recursive (cdr keys) record)
'#f))
'#f)))
(lookup-recursive keys local-table))
(define (insert! keys value)
(define (insert-recursive! keys table)
(let ((record (assoc (car keys) (cdr table))))
(if record
(if (null? (cdr keys))
(set-cdr! record value)
(if (pair? (cdr record))
(insert-recursive! (cdr keys) record)
; this can be abstracted in recursive make
(begin
(set-cdr! record
(cons (cons (cadr keys) '()) '()))
(insert-recursive! (cdr keys) record))))
; no record found
(if (null? (cdr keys))
(set-cdr! table
(cons (cons (car keys) value) (cdr table)))
; this can be abstracted in a recursive make
(begin
(set-cdr! table
(cons (cons (car keys) '()) (cdr table)))
(insert-recursive! keys table))))))
(insert-recursive! keys local-table))
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation -- TABLE" m))))
dispatch))
; some examples to se if this actually works
(define t (make-table))
(define put (t 'insert-proc!))
(define get (t 'lookup-proc))
(put '(a) 10)
(put '(a b) 5)
(output (get '(a)))
(put '(a b d) 6)
(put '(a b e f) 8)
(output (get '(a)))
(output (get '(a b c)))
(output (get '(a b d)))
(output (get '(a b e)))
(output (get '(a b e f)))
| false |
e2636729a20b7cc717acd89c0dbe2099ec2b775d
|
894c73f545af0ae7c4ff8e1689fb06ced2ce5d9e
|
/build-included-binary-file.ss
|
4793bf589e49812259550ac55a8c14c93561d9cf
|
[
"0BSD"
] |
permissive
|
t-triobox/chez-exe
|
5300fb0d3d883892e6fa28518b8b62b978cbf3d0
|
25f52a8137331f3a65c16b40e260b8f72dfe45ef
|
refs/heads/master
| 2022-12-12T08:27:07.141428 | 2020-08-13T03:52:52 | 2020-08-13T03:52:52 | 254,805,397 | 0 | 0 |
NOASSERTION
| 2020-08-13T03:52:53 | 2020-04-11T06:14:18 | null |
UTF-8
|
Scheme
| false | false | 126 |
ss
|
build-included-binary-file.ss
|
(include "utils.ss")
(define args (command-line-arguments))
(build-included-binary-file (car args) (cadr args) (caddr args))
| false |
c500362412e293da2255d44fc0394d9e8bdb467f
|
923209816d56305004079b706d042d2fe5636b5a
|
/sitelib/http/header-field/if-range.scm
|
5da8ea18a071d99685c46c1e3e842b885dfcc1c7
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
tabe/http
|
4144cb13451dc4d8b5790c42f285d5451c82f97a
|
ab01c6e9b4e17db9356161415263c5a8791444cf
|
refs/heads/master
| 2021-01-23T21:33:47.859949 | 2010-06-10T03:36:44 | 2010-06-10T03:36:44 | 674,308 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 313 |
scm
|
if-range.scm
|
(library (http header-field if-range)
(export If-Range)
(import (rnrs (6))
(http abnf)
(http date-time)
(http entity-tag))
;;; 14.27 If-Range
(define If-Range
(seq (string->rule "If-Range") (char->rule #\:) *LWS ; implicit *LWS
(bar entity-tag HTTP-date)))
)
| false |
49733ee61a7f805e6033a66d3b754d011ea0b1c0
|
e75694971a8d65a860e49d099aba868e1b7ec664
|
/a1.scm
|
2fe0f126d20e424556082e8920f317b6a933d928
|
[] |
no_license
|
telnet23/sicp
|
d29088e1bdef7ede3cf5805559e0edb3b0ef54fe
|
a85fa7f17c7485163c9484ed5709d6ec64e87aaa
|
refs/heads/master
| 2023-02-20T09:20:38.216645 | 2019-04-30T20:15:12 | 2019-04-30T20:15:12 | 331,790,140 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 757 |
scm
|
a1.scm
|
"problem 1. (a)"
(define (usd-to-euro usd) (* usd 0.88))
(usd-to-euro 250)
"problem 1. (b)"
(define (euro-to-yen euro) (* euro 124.91))
(euro-to-yen 250)
"problem 1. (c)"
(define (usd-to-yen usd) (euro-to-yen (usd-to-euro usd)))
(usd-to-yen 250)
"problem 2. (a)"
(define pi 3.14159)
"problem 2. (b)"
(define (area-of-circle r) (* pi
(* r r)))
"problem 3. (c)"
(define (surface-area-of-sphere r) (* 4
(area-of-circle r)))
"problem 3. (d)"
(define (volume-of-sphere r) (/ (* r
(surface-area-of-sphere r))
3))
"problem 4. (a)"
(define (det2x2 a b c d) (- (* a d)
(* b c)))
(det2x2 -3 1 2 7)
| false |
c0fb48a0304b7b3b235079340198070bf6bf34d4
|
f4aeaa0812ac15d5a8d2cb6da75ac335c3cf5cf4
|
/test-check.scm
|
366dc99c9dce1314e617db615e3bea9a2da06571
|
[
"MIT"
] |
permissive
|
orchid-hybrid/microKanren-sagittarius
|
13f7916f8ef7c946cefeb87e9e52d6d4a5dfe6c9
|
9e740bbf94ed2930f88bbcf32636d3480934cfbb
|
refs/heads/master
| 2021-01-13T01:54:20.589391 | 2015-06-13T12:40:14 | 2015-06-13T12:40:14 | 29,868,626 | 12 | 4 | null | 2015-02-12T07:11:25 | 2015-01-26T16:01:10 |
Scheme
|
UTF-8
|
Scheme
| false | false | 510 |
scm
|
test-check.scm
|
(define-syntax test-check
(syntax-rules ()
((_ title tested-expression expected-result)
(begin
(display "Testing ")
(display title)
(newline)
(let* ((expected expected-result)
(produced tested-expression))
(or (equal? expected produced)
(error (list title 'failed
(list 'input 'tested-expression)
(list 'expected expected)
(list 'produced produced)))))))))
| true |
ef27c7642749bfddb4530e7a4a0f0eb047c40b01
|
5debba08fe46cfceb66fb0a57c7c8ce906214f88
|
/appinventor/blocklyeditor/tests/com/google/appinventor/blocklyeditor/data/makeQuiz/Screen1.scm
|
7af44e64c7fd6c97559bd73c3b2cd5932d0997ff
|
[
"Apache-2.0"
] |
permissive
|
mit-cml/appinventor-extensions
|
0b45274697c48882de1abb816b72a15fbee8b9ff
|
e33b14041447cd47ca3d52dec6ef9bab068c51c8
|
refs/heads/master
| 2023-08-09T23:58:28.228407 | 2022-09-16T17:54:41 | 2022-09-16T17:54:41 | 100,065,339 | 80 | 105 |
Apache-2.0
| 2023-07-28T19:34:33 | 2017-08-11T19:46:44 |
Java
|
UTF-8
|
Scheme
| false | false | 1,326 |
scm
|
Screen1.scm
|
#|
$JSON
{"YaVersion":"79","Source":"Form","Properties":{"$Name":"Screen1","$Type":"Form","$Version":"11","Uuid":"0","BackgroundColor":"&HFFCCCCCC","Title":"Make-A-Quiz","$Components":[{"$Name":"Label4","$Type":"Label","$Version":"2","Uuid":"47695041","FontItalic":"True","Text":"enter a new question-answer pair:"},{"$Name":"TableArrangement1","$Type":"TableArrangement","$Version":"1","Uuid":"-1684518506","$Components":[{"$Name":"Label1","$Type":"Label","$Version":"2","Uuid":"-1800823994","Text":"Question:","Column":"0","Row":"0"},{"$Name":"Label2","$Type":"Label","$Version":"2","Uuid":"-1182441001","Text":"Answer:","Column":"0","Row":"1"},{"$Name":"QuestionText","$Type":"TextBox","$Version":"4","Uuid":"1406127130","Hint":"Enter a question","Column":"1","Row":"0"},{"$Name":"AnswerText","$Type":"TextBox","$Version":"4","Uuid":"1613926125","Hint":"enter answer","Column":"1","Row":"1"}]},{"$Name":"SubmitButton","$Type":"Button","$Version":"5","Uuid":"-966805461","Text":"Submit"},{"$Name":"Label3","$Type":"Label","$Version":"2","Uuid":"1314694677","FontBold":"True","FontSize":"18.0","Text":"Quiz Questions and Answers"},{"$Name":"QuestionsAnswersLabel","$Type":"Label","$Version":"2","Uuid":"1953962099"},{"$Name":"TinyWebDB1","$Type":"TinyWebDB","$Version":"2","Uuid":"-338955949","ServiceURL":"foobar.com"}]}}
|#
| false |
4ae8309552675092ec3fdb7d6b1e23b6640bec16
|
6b8bee118bda956d0e0616cff9ab99c4654f6073
|
/sdk-ex/refs/_stepbystep/_test.scm
|
a25e910bb266b37f1163aca8254bd2d17f84651d
|
[] |
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
|
Scheme
| false | false | 4,154 |
scm
|
_test.scm
|
#lang scheme
(require scheme/foreign
scheme/system
mred
mzlib/class
sgl
sgl/gl
sgl/gl-vectors
sgl/gl-types
"../../../schcuda/gl-1.5.ss"
"../../../schcuda/ffi-ext.ss"
"../../../schcuda/scuda.ss"
"../../schcuda/suda-set-env.ss"
"../../../schcuda/cuda_h.ss"
"../../../schcuda/cudaGL_h.ss"
"../../../schcuda/glew_h.ss")
(unsafe!)
(define window_width 512)
(define window_height 512)
(define mesh_width 256)
(define mesh_height 256)
(define vbo-init #f)
(define anim 1.0)
(define cudaGLInit%
(class* canvas% ()
(inherit refresh with-gl-context)
(define/override (on-size width height)
(with-gl-context
(lambda ()
;; VBO init and registration to cuda
(unless vbo-init
(let* ([cubin-name (generate-cubin #"data/_test_kernel.cubin")]
[cuDevice (suda-init-devices 0)])
(let-values ([(cuContext l-func)
(load-kernel-driver cuDevice cubin-name #"kernel")])
(let* ([glewv (glewInit)]
[size (* mesh_width mesh_height 4 (ctype-sizeof _float))]
[vb (cvector-ref (glGenBuffers 1) 0)]
[bb (glBindBuffer GL_ARRAY_BUFFER vb)]
[bd (glBufferData GL_ARRAY_BUFFER
size
(malloc 1 _int)
GL_DYNAMIC_DRAW)]
[bb2 (glBindBuffer GL_ARRAY_BUFFER 0)]
[resulti (cuGLInit)])
(printf "cuDevice, vbo = ~s ~s\n" cuDevice vb)
(printf "init result = ~s \n" resulti)
(let* ([resultr (cuGLRegisterBufferObject vb)])
(printf "register result = ~s\n" resultr)
(let*-values ([(resultm dv size) (cuGLMapBufferObject vb)])
(let* ([func (car l-func)]
[block-size 8]
[grid-w (/ mesh_width block-size)]
[grid-h (/ mesh_height block-size)]
[lst-offs (offsets-ctype (list _int _uint _uint _float))])
(printf "result: MapBufferObject = ~s\n" resultm)
(let*-values ([(resultbs func)
(cuFuncSetBlockShape func block-size block-size 1)]
[(result0 func) (cuParamSeti func 0 dv)]
[(result1 func) (cuParamSeti func (list-ref lst-offs 0) mesh_width)]
[(result2 func) (cuParamSeti func (list-ref lst-offs 1) mesh_height)]
[(result3 func) (cuParamSetf func (list-ref lst-offs 2) anim)]
[(result4 func) (cuParamSetSize func (list-ref lst-offs 3))])
(printf "result: ParamSet dv: ~s\n" result0)
(printf "result: ParamSet width: ~s\n" result1)
(printf "result: ParamSet height: ~s\n" result2)
(printf "result: ParamSet anim: ~s\n" result3)
(printf "result: ParamSet f: ~s\n" result4)
(let* ([resultl (cuLaunchGrid func grid-w grid-h)])
(printf "RESULT(cuLaunchGrid):~s\n" resultl)
#f)
(cuGLUnmapBufferObject vb)))
#f
)))))
;; flag reset.
(set! vbo-init #t)
; (cutCheckErrorGL "simpleGLDrv.scm" 0)
))))
(super-instantiate () (style '(gl no-autoclear)))
))
(define (runClass)
(let* ([f (make-object frame% "test" #f)]
[c (instantiate cudaGLInit% (f)
(min-width 30)
(min-height 40))])
(send f show #t)))
(runClass)
| false |
0cbf5062172899a62f7cfef0064b3be70d7630b6
|
bf1c9803ae38f9aad027fbe4569ccc6f85ba63ab
|
/chapter_1/1.3.Formulating.Abstractions.with.Higher-Order.Procedures/ex_1.32.scm
|
bced004f8088bc7ec76919fe9dec60f3c85a8ce5
|
[] |
no_license
|
mehese/sicp
|
7fec8750d3b971dd2383c240798dbed339d0345a
|
611b09280ab2f09cceb2479be98ccc5403428c6c
|
refs/heads/master
| 2021-06-12T04:43:27.049197 | 2021-04-04T22:22:47 | 2021-04-04T22:23:12 | 161,924,666 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,609 |
scm
|
ex_1.32.scm
|
#lang sicp
(define (even? n)
(= 0 (remainder n 2)))
(define (square x)
(* x x))
(define (cube x)
(* x x x))
(define (inc x)
(+ x 1))
;; Recursive definition sum
(define (sum-rec term a next b)
(if (> a b)
0
(+ (term a)
(sum-rec term (next a) next b))))
;; Iterative definition sum
(define (sum-iter term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (+ result (term a)))))
(iter a 0))
;; Recursive definition prod
(define (prod-rec term a next b)
(if (> a b)
1
(* (term a) (prod-rec term (next a) next b))))
;; Iterative definition prod
(define (prod-iter term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (* (term a) result))))
(iter a 1))
;; Recursive definition
(define (accumulate-rec combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a) (accumulate-rec combiner null-value term (next a) next b))))
;; Iterative definition
(define (accumulate-iter combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (term a) result))))
(iter a null-value))
(sum-iter identity 1 inc 11)
(sum-rec identity 1 inc 11)
(accumulate-rec + 0 identity 1 inc 11)
(accumulate-iter + 0 identity 1 inc 11)
(sum-iter square 1 inc 11)
(sum-rec square 1 inc 11)
(accumulate-rec + 0 square 1 inc 11)
(accumulate-iter + 0 square 1 inc 11)
(prod-iter identity 1 inc 5)
(prod-rec identity 1 inc 5)
(accumulate-rec * 1 identity 1 inc 5)
(accumulate-iter * 1 identity 1 inc 5)
| false |
bcd32caf39a1ec977f92704eaf6d33bb5b02a41a
|
222b42ba803bfecd4ec31166dd2be107a840f2bd
|
/misc/delete.scm
|
4cf5fad64aeaa2ca70d3c78cf4d2e141c18accc5
|
[] |
no_license
|
ab3250/ablib
|
83512c2c2cadd0eb49ad534548c058e3ed119d4c
|
887c8661ce99e8edfe89bcf707400e55c3943dd4
|
refs/heads/master
| 2023-06-12T13:36:49.487467 | 2021-07-11T13:29:45 | 2021-07-11T13:29:45 | 384,955,137 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 431 |
scm
|
delete.scm
|
(define delete
(case-lambda
((x lis)
(delete x lis equal?))
((x lis elt=)
(let recur ((lis lis))
(if (eqv? lis '()) lis
(let ((head (car lis))
(tail (cdr lis)))
(if (not (elt= x head))
(let ((new-tail (recur tail)))
(if (eq? tail new-tail) lis
(cons head new-tail)))
(recur tail))))))))
| false |
4c5f68d2c262882be4b5c09476dd3d2e6939279e
|
fe82ca017f34aabbbda0ec9bb76bdc930554a7c6
|
/utils.rkt
|
50acd11e98b4f860d49ac55754e6553f072491a1
|
[] |
no_license
|
fare/lil-ilc2012
|
260981308a614030134bffdeac95be0c6ab14194
|
220a9aa9c5a2c0bdbbb2afa4873d31be4164c461
|
refs/heads/master
| 2020-12-24T16:32:45.111342 | 2016-05-15T03:44:36 | 2016-05-15T03:44:36 | 5,059,441 | 14 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,959 |
rkt
|
utils.rkt
|
#lang at-exp racket
;;-*- Scheme -*-
;;(display "In utils.rkt!\n")
(require
scribble/core
scribble/decode
scribble/base
scriblib/autobib
scribble/manual
scribble/bnf
(for-syntax syntax/parse))
(provide
XXX IPS CL gf gfs LIL
cl clcode clblock <>
~cite define-bib generate-bib
long short abstract-only backend sf
pdfonly htmlonly pdflinebreak q)
;;(define-syntax-rule (~cite what ...) "")
(define abstract-only (make-parameter #f))
(define backend (make-parameter '#:pdf))
(define-syntax-rule (long x ...) (unless (abstract-only) (list x ...)))
(define-syntax-rule (short x ...) (when (abstract-only) (list x ...)))
(define (IPS) "Interface-Passing Style")
(define (CL) "Common Lisp")
(define (LIL) "Lisp Interface Library")
(define (gf) "generic function")
(define (gfs) "generic functions")
(define-syntax (clblock stx)
(syntax-parse stx
[(_ #:line-numbers ln str ...)
#'@nested[#:style "smaller"]{
@codeblock[;;#:keep-lang-line? #f
#:line-numbers ln
#:line-number-sep 3
str ...]}]
[(_ str ...)
#'(clblock #:line-numbers 0 str ...)]))
(define-syntax (clcode stx)
(syntax-parse stx
[(_ str ...) #'(clblock #:line-numbers #f str ...)]))
(define-syntax-rule (cl str ...)
@code[#|#:lang "cl"|# str ...])
(define-syntax-rule (<> x) (cl "<" x ">"))
(define-syntax-rule (pdfonly body ...)
(case (backend) ((#:pdf) body ...)))
(define-syntax-rule (htmlonly body ...)
(case (backend) ((#:html) body ...)))
(define (pdflinebreak) (pdfonly (linebreak)))
(define-cite ~cite cite-noun generate-bib)
(define-syntax-rule (define-bib name stuff ...)
(define name (make-bib stuff ...)))
;;(define-syntax-rule (p+ x ...) (list x ...))
(define-syntax-rule (XXX x ...) '())
(define (sf . str) (make-element 'sf (decode-content str)))
(define (ldquo) 'ldquo)
(define (rdquo) 'rdquo)
(define (q . content) (list (ldquo) content (rdquo)))
| true |
a7fe55e8db0b9e1eb4c3ace54ff7b8ffb11b7738
|
c157305e3b08b76c2f4b0ac4f9c04b435097d0dc
|
/eopl2e/code/interps/3-8name.scm
|
728adfa725a4a5d7fc9dfd0f27b789dd7c824986
|
[] |
no_license
|
rstewart2702/scheme_programs
|
a5e91bd0e1587eac3859058da18dd9271a497721
|
767d019d84896569f2fc02de95925b05a38cac4d
|
refs/heads/master
| 2021-05-02T02:01:01.964797 | 2014-03-31T19:02:36 | 2014-03-31T19:02:36 | 13,077,035 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 12,206 |
scm
|
3-8name.scm
|
;; 3-8name.scm : interp with call by name
(let ((time-stamp "Time-stamp: <2001-05-10 16:14:16 dfried>"))
(eopl:printf "3-8name.scm - interp with call by name ~a~%"
(substring time-stamp 13 29)))
;;;;;;;;;;;;;;;; top level and tests ;;;;;;;;;;;;;;;;
(define run
(lambda (string)
(eval-program (scan&parse string))))
(define run-all
(lambda ()
(run-experiment run use-execution-outcome
'(lang3-1 lang3-5 lang3-6 lang3-7 lang3-8name) all-tests)))
(define run-one
(lambda (test-name)
(run-test run test-name)))
;; needed for testing
(define equal-external-reps? equal?)
;;;;;;;;;;;;;;;; grammatical specification ;;;;;;;;;;;;;;;;
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)))
(define the-grammar
'((program (expression) a-program)
(expression (number) lit-exp)
(expression (identifier) var-exp)
(expression
(primitive "(" (separated-list expression ",") ")")
primapp-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression
("let" (arbno identifier "=" expression) "in" expression)
let-exp)
(expression
("proc" "(" (separated-list identifier ",") ")" expression)
proc-exp)
(expression
("(" expression (arbno expression) ")")
app-exp)
(expression ("set" identifier "=" expression) varassign-exp)
(expression
("begin" expression (arbno ";" expression) "end")
begin-exp)
(expression
("letrec"
(arbno identifier "(" (separated-list identifier ",") ")"
"=" expression)
"in" expression)
letrec-exp)
(primitive ("+") add-prim)
(primitive ("-") subtract-prim)
(primitive ("*") mult-prim)
(primitive ("add1") incr-prim)
(primitive ("sub1") decr-prim)
(primitive ("zero?") zero-test-prim)
))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;;
(define eval-program
(lambda (pgm)
(cases program pgm
(a-program (body)
(eval-expression body (init-env))))))
(define eval-expression ; exp x env -> expval
(lambda (exp env)
(cases expression exp
(lit-exp (datum) datum)
(var-exp (id) (apply-env env id))
(varassign-exp (id rhs-exp)
(begin
(setref!
(apply-env-ref env id)
(eval-expression rhs-exp env))
1))
(primapp-exp (prim rands)
(let ((args (eval-primapp-exp-rands rands env)))
(apply-primitive prim args)))
(if-exp (test-exp true-exp false-exp)
(if (true-value? (eval-expression test-exp env))
(eval-expression true-exp env)
(eval-expression false-exp env)))
(proc-exp (ids body) (closure ids body env))
(begin-exp (exp1 exps)
(let loop ((acc (eval-expression exp1 env))
(exps exps))
(if (null? exps) acc
(loop (eval-expression (car exps) env) (cdr exps)))))
(let-exp (ids rands body)
(let ((args (eval-let-exp-rands rands env)))
(eval-expression body (extend-env ids args env))))
(app-exp (rator rands)
(let ((proc (eval-expression rator env))
(args (eval-rands rands env)))
(if (procval? proc)
(apply-procval proc args)
(eopl:error 'eval-expression
"Attempt to apply non-procedure ~s" proc))))
(letrec-exp (proc-names idss bodies letrec-body)
(eval-expression letrec-body
(extend-env-recursively proc-names idss bodies env)))
)))
(define eval-primapp-exp-rands
(lambda (rands env)
(map (lambda (x) (eval-expression x env)) rands)))
(define eval-let-exp-rands
(lambda (rands env)
(map (lambda (x) (eval-let-exp-rand x env)) rands)))
(define eval-let-exp-rand
(lambda (rand env)
(direct-target (eval-expression rand env))))
(define eval-rands
(lambda (rands env)
(map (lambda (x) (eval-rand x env)) rands)))
(define eval-rand
(lambda (rand env)
; (eopl:printf "eval-rand: rand = ~s ~%" rand)
; (eopl:pretty-print (printable-env env))
(let ((ans (cases expression rand
(lit-exp (datum) (direct-target datum))
(var-exp (id)
(let ((ref (apply-env-ref env id)))
(cases target (primitive-deref ref)
(direct-target (expval) (indirect-target ref))
(indirect-target (ref1)
(indirect-target ref1))
(thunk-target (exp env) (indirect-target ref)))))
(proc-exp (ids body)
(direct-target (closure ids body env)))
(else (thunk-target rand env)))))
; (eopl:printf "eval-rand succeeded ~%")
ans)))
(define apply-primitive
(lambda (prim args)
(cases primitive prim
(add-prim () (+ (car args) (cadr args)))
(subtract-prim () (- (car args) (cadr args)))
(mult-prim () (* (car args) (cadr args)))
(incr-prim () (+ (car args) 1))
(decr-prim () (- (car args) 1))
(zero-test-prim () (if (zero? (car args)) 1 0))
)))
(define init-env
(lambda ()
(extend-env
'(i v x)
(map direct-target '(1 5 10))
(empty-env))))
;;;;;;;;;;;;;;;; booleans ;;;;;;;;;;;;;;;;
(define true-value?
(lambda (x)
(not (zero? x))))
;;;;;;;;;;;;;;;; procedures ;;;;;;;;;;;;;;;;
(define-datatype procval procval?
(closure
(ids (list-of symbol?))
(body expression?)
(env environment?)))
(define apply-procval
(lambda (proc args)
(cases procval proc
(closure (ids body env)
(eval-expression body (extend-env ids args env))))))
;;;;;;;;;;;;;;;; references ;;;;;;;;;;;;;;;;
;; a reference is a pointer to a vector containing targets.
;; the order of fields is funny, but leads to easier debugging.
(define-datatype reference reference?
(a-ref
(position integer?)
(vec (vector-of target?))))
(define-datatype target target?
(direct-target
(expval expval?))
(indirect-target
(ref ref-to-direct-target?))
(thunk-target ; by name
(exp expression?)
(env environment?)))
(define expval?
(lambda (x)
(or (number? x) (procval? x))))
(define vector-of ; ignores argument
(lambda (pred) vector?))
(define ref-to-direct-target?
(lambda (x)
(and
(reference? x)
(cases target (primitive-deref x)
(direct-target (v) #t)
(indirect-target (p) #f)
(thunk-target (exp env) #t)))))
(define primitive-deref
(lambda (ref)
(cases reference ref
(a-ref (pos vec) (vector-ref vec pos)))))
(define primitive-setref!
(lambda (ref val)
(cases reference ref
(a-ref (pos vec) (vector-set! vec pos val)))))
(define deref
(lambda (ref)
(let ((t1 (primitive-deref ref)))
(cases target t1
(direct-target (val) val)
(indirect-target (ref)
(let ((t2 (primitive-deref ref)))
(cases target t2
(direct-target (val) val)
(thunk-target (exp env) (eval-thunk ref))
(indirect-target (p)
(eopl:error 'deref "Illegal reference")))))
(thunk-target (exp env) (eval-thunk ref))))))
(define eval-thunk
(lambda (ref)
(cases target (primitive-deref ref)
(thunk-target (exp env)
(eval-expression exp env))
(else (eopl:error 'eval-thunk "Impossible!")))))
(define setref!
(lambda (ref expval)
(let ((t1 (primitive-deref ref)))
(cases target t1
(direct-target (val1)
(primitive-setref! ref (direct-target expval)))
(indirect-target (ref1)
(primitive-setref! ref1 (direct-target expval)))
(thunk-target (exp env)
(primitive-setref! ref (direct-target expval)))))))
;;;;;;;;;;;;;;;; environments ;;;;;;;;;;;;;;;;
(define-datatype environment environment?
(empty-env-record)
(extended-env-record
(syms (list-of symbol?))
(vec vector?) ; can use this for anything.
(env environment?))
)
(define empty-env
(lambda ()
(empty-env-record)))
(define extend-env
(lambda (syms vals env)
; (eopl:printf "extend-env: syms = ~s vals =" syms)
; (eopl:pretty-print vals)
(if ((list-of target?) vals)
(extended-env-record syms (list->vector vals) env)
(begin
(eopl:printf "extend-env: bad values ~%")
(eopl:pretty-print vals)
(eopl:error 'extend-env "")))))
(define apply-env-ref
(lambda (env sym)
(cases environment env
(empty-env-record ()
(eopl:error 'apply-env-ref "No binding for ~s" sym))
(extended-env-record (syms vals env)
(let ((pos (rib-find-position sym syms)))
(if (number? pos)
(a-ref pos vals)
(apply-env-ref env sym)))))))
(define apply-env
(lambda (env sym)
(deref (apply-env-ref env sym))))
(define extend-env-recursively
(lambda (proc-names idss bodies old-env)
(let ((len (length proc-names)))
(let ((vec (make-vector len)))
(let ((env (extended-env-record proc-names vec old-env)))
(for-each
(lambda (pos ids body)
(vector-set! vec pos
(direct-target ; change for by-ref
(closure ids body env))))
(iota len) idss bodies)
env)))))
(define rib-find-position
(lambda (sym los)
(list-find-position sym los)))
(define list-find-position
(lambda (sym los)
(list-index (lambda (sym1) (eqv? sym1 sym)) los)))
(define list-index
(lambda (pred ls)
(cond
((null? ls) #f)
((pred (car ls)) 0)
(else (let ((list-index-r (list-index pred (cdr ls))))
(if (number? list-index-r)
(+ list-index-r 1)
#f))))))
(define iota
(lambda (end)
(let loop ((next 0))
(if (>= next end) '()
(cons next (loop (+ 1 next)))))))
(define difference
(lambda (set1 set2)
(cond
((null? set1) '())
((memv (car set1) set2)
(difference (cdr set1) set2))
(else (cons (car set1) (difference (cdr set1) set2))))))
;;; for debugging:
(define printable-env
(lambda (env)
(cases environment env
(empty-env-record () '())
(extended-env-record (syms vals env)
(cons
(map
(lambda (sym)
(let ((pos (rib-find-position sym syms)))
(if (number? pos)
(let ((t1 (vector-ref vals pos)))
(cases target t1
(direct-target (val1)
(list sym (list 'my-direct-target
(printable-expval val1))))
(indirect-target (ref1)
(list sym (list 'my-indirect-target
(printable-expval (deref
ref1)))))
(thunk-target (exp env)
(list sym (list 'my-thunk-target
exp
(printable-env env))))))
(eopl:error 'printable))))
syms)
(printable-env env))))))
(define printable-expval
(lambda (v)
(if (procval? v)
(cases procval v
(closure (ids body env)
(list 'my-closure ids body (printable-env env))))
v)))
| false |
f3156d8c9b9f779a4bc8fe9d2ae2a2c7b2b1d1fa
|
26aaec3506b19559a353c3d316eb68f32f29458e
|
/apps/DemoCamera/main.scm
|
a9a9efa0ac222f4da98d4e4769ebb41cf82c167b
|
[
"BSD-3-Clause"
] |
permissive
|
mdtsandman/lambdanative
|
f5dc42372bc8a37e4229556b55c9b605287270cd
|
584739cb50e7f1c944cb5253966c6d02cd718736
|
refs/heads/master
| 2022-12-18T06:24:29.877728 | 2020-09-20T18:47:22 | 2020-09-20T18:47:22 | 295,607,831 | 1 | 0 |
NOASSERTION
| 2020-09-15T03:48:04 | 2020-09-15T03:48:03 | null |
UTF-8
|
Scheme
| false | false | 4,543 |
scm
|
main.scm
|
#|
LambdaNative - a cross-platform Scheme framework
Copyright (c) 2009-2014, University of British Columbia
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
* Neither the name of the University of British Columbia nor
the names of its contributors may be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|#
;; camera example
(define gui #f)
(define background #f)
(define default:background (list 4 4 (glCoreTextureCreate 4 4 (make-u8vector 16 #xff)) 0.1 0.1 .9 .9))
(define camera-image (string-append (system-directory) (system-pathseparator) "vidcam.jpg"))
(define camera-image2 (string-append (system-directory) (system-pathseparator) "vidcam.png"))
(define vid-location (string-append (system-directory) (system-pathseparator) "example.mp4"))
(define lastmodtime 0.)
;; look for a new jpeg from the camera, create a downsampled png, and load that as a texture
(define (autoload)
(let* ((fileinfo (if (file-exists? camera-image) (file-info camera-image) #f))
(modtime (if fileinfo (time->seconds (file-info-last-modification-time fileinfo)) #f)))
(if (and gui background modtime (> modtime lastmodtime))
(let* ((gdf (gdFileOpen camera-image "r"))
(gd (gdImageCreateFromJpeg gdf))
(w (gdImageSX gd))
(h (gdImageSY gd))
(w2 256)
(h2 (fix (* w2 (/ h w))))
(gdf2 (gdFileOpen camera-image2 "w"))
(gd2 (gdImageCreateTrueColor w2 h2)))
(gdImageCopyResampled gd2 gd 0 0 0 0 w2 h2 w h)
(gdImagePng gd2 gdf2)
(gdImageDestroy gd)
(gdImageDestroy gd2)
(gdFileClose gdf)
(gdFileClose gdf2)
(let ((img (if (file-exists? camera-image2) (png->img camera-image2) #f)))
(glgui-widget-set! gui background 'image (if img img default:background)))
(set! lastmodtime modtime)
))))
(main
;; initialization
(lambda (w h)
(make-window 320 480)
(glgui-orientation-set! GUI_PORTRAIT)
(set! gui (make-glgui))
(let ((w (glgui-width-get))
(h (glgui-height-get)))
(set! background (glgui-pixmap gui 0 0 default:background w h))
(camera-set-max-length-video 45)
(let* ((bw 150) (bh 50)
(bx (/ (- w bw) 2.))
(by (/ (- h bh) 2.)))
(glgui-button-string gui bx (+ by (* bh 2)) bw bh "Take Picture" ascii_18.fnt
(lambda (un . used) (camera-start camera-image)))
(glgui-button-string gui bx by bw bh "Take Video" ascii_18.fnt
(lambda (un . used) (camera-start-video vid-location)))
(glgui-button-string gui bx (- by (* bh 2)) bw bh "Watch Video" ascii_18.fnt
(lambda (un . used) (videoplayer vid-location))))
)
(if (file-exists? camera-image) (delete-file camera-image))
(if (file-exists? camera-image2) (delete-file camera-image2))
(let ((logdir (string-append (system-directory) "/log")))
(if (not (file-exists? logdir)) (create-directory logdir)))
)
;; events
(lambda (t x y)
(autoload)
(if (= t EVENT_KEYPRESS) (begin
(if (= x EVENT_KEYESCAPE) (terminate))))
(glgui-event gui t x y))
;; termination
(lambda () #t)
;; suspend
(lambda () (glgui-suspend))
;; resume
(lambda () (glgui-resume))
)
;; eof
| false |
dfb7ab4ce795d2639788358a1dfbf4eb541dc952
|
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
|
/packages/srfi/tests/and-let%2a.sps
|
2b2cdafc1a7c8461afb4a96d0dd265149259cff8
|
[
"X11-distribute-modifications-variant",
"MIT"
] |
permissive
|
evilbinary/scheme-lib
|
a6d42c7c4f37e684c123bff574816544132cb957
|
690352c118748413f9730838b001a03be9a6f18e
|
refs/heads/master
| 2022-06-22T06:16:56.203827 | 2022-06-16T05:54:54 | 2022-06-16T05:54:54 | 76,329,726 | 609 | 71 |
MIT
| 2022-06-16T05:54:55 | 2016-12-13T06:27:36 |
Scheme
|
UTF-8
|
Scheme
| false | false | 2,862 |
sps
|
and-let%2a.sps
|
#!r6rs
;; Copyright 2010 Derick Eddington. My MIT-style license is in the file named
;; LICENSE from the original collection this file is distributed with.
(import
(rnrs)
(rnrs eval)
(srfi :2 and-let*)
(srfi :78 lightweight-testing))
(define-syntax expect
(syntax-rules ()
((_ expr result)
(check expr => result))))
(define-syntax must-be-a-syntax-error
(syntax-rules ()
((_ expr)
(check
(guard (ex (#T (syntax-violation? ex)))
(eval 'expr (environment '(rnrs) '(srfi :2 and-let*)))
'unexpected-return)
=> #T))))
;; Taken from the reference implementation tests
(expect (and-let* () 1) 1)
(expect (and-let* () 1 2) 2)
(expect (and-let* () ) #T)
(expect (let ((x #F)) (and-let* (x))) #F)
(expect (let ((x 1)) (and-let* (x))) 1)
(expect (and-let* ((x #F)) ) #F)
(expect (and-let* ((x 1)) ) 1)
(must-be-a-syntax-error (and-let* ( #F (x 1))) )
(expect (and-let* ( (#F) (x 1)) ) #F)
(must-be-a-syntax-error (and-let* (2 (x 1))) )
(expect (and-let* ( (2) (x 1)) ) 1)
(expect (and-let* ( (x 1) (2)) ) 2)
(expect (let ((x #F)) (and-let* (x) x)) #F)
(expect (let ((x "")) (and-let* (x) x)) "")
(expect (let ((x "")) (and-let* (x) )) "")
(expect (let ((x 1)) (and-let* (x) (+ x 1))) 2)
(expect (let ((x #F)) (and-let* (x) (+ x 1))) #F)
(expect (let ((x 1)) (and-let* (((positive? x))) (+ x 1))) 2)
(expect (let ((x 1)) (and-let* (((positive? x))) )) #T)
(expect (let ((x 0)) (and-let* (((positive? x))) (+ x 1))) #F)
(expect (let ((x 1)) (and-let* (((positive? x)) (x (+ x 1))) (+ x 1))) 3)
;; Derick thinks variable shadowing should be allowed, because it's a "let*".
#;(must-be-a-syntax-error
(let ((x 1)) (and-let* (((positive? x)) (x (+ x 1)) (x (+ x 1))) (+ x 1))))
(expect (let ((x 1)) (and-let* (x ((positive? x))) (+ x 1))) 2)
(expect (let ((x 1)) (and-let* ( ((begin x)) ((positive? x))) (+ x 1))) 2)
(expect (let ((x 0)) (and-let* (x ((positive? x))) (+ x 1))) #F)
(expect (let ((x #F)) (and-let* (x ((positive? x))) (+ x 1))) #F)
(expect (let ((x #F)) (and-let* ( ((begin x)) ((positive? x))) (+ x 1))) #F)
(expect (let ((x 1)) (and-let* (x (y (- x 1)) ((positive? y))) (/ x y))) #F)
(expect (let ((x 0)) (and-let* (x (y (- x 1)) ((positive? y))) (/ x y))) #F)
(expect (let ((x #F)) (and-let* (x (y (- x 1)) ((positive? y))) (/ x y))) #F)
(expect (let ((x 3)) (and-let* (x (y (- x 1)) ((positive? y))) (/ x y))) 3/2)
;; Derick's additional tests
(must-be-a-syntax-error (and-let* (("oops" 1))))
(must-be-a-syntax-error (and-let* ((x 1 2))))
(must-be-a-syntax-error (and-let* ((x 1) . oops)))
(expect (let ((x 1))
(and-let* ((x (+ x 1))
(x (+ x 1))
(x (+ x 1)))
(+ x 1)))
5)
(expect (and-let* () (define x 1) (- x)) -1)
(expect (and-let* ((x 2) (y (+ 1 x))) (define z (* x y)) (/ z)) 1/6)
(check-report)
| true |
4b6fa602a0bc2864a14d73269495ade5a947a44b
|
dae624fc36a9d8f4df26f2f787ddce942b030139
|
/chapter-07/receive.scm
|
9c532d7dad0a273739b7fb8619dd2f066ce93284
|
[
"MIT"
] |
permissive
|
hshiozawa/gauche-book
|
67dcd238c2edeeacb1032ce4b7345560b959b243
|
2f899be8a68aee64b6a9844f9cbe83eef324abb5
|
refs/heads/master
| 2020-05-30T20:58:40.752116 | 2019-10-01T08:11:59 | 2019-10-01T08:11:59 | 189,961,787 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 792 |
scm
|
receive.scm
|
(min&max 3 1 2)
(receive (min-val max-val)
(min&max 3 1 2)
(list min-val max-val))
(receive (min-val . rest)
(min&max 3 1 2)
(list min-val rest))
(receive all-values
(min&max 3 1 2)
all-values)
(receive (all-values)
(min&max 3 1 2)
all-values) ; error
(use srfi-11)
(let-values (((min-val max-val) (min&max 3 1 2)))
(format #t "max: ~s\nmin: ~s\n" max-val min-val))
(let ((a 3)
(b 4))
(let-values (((a b) (min&max 0 100))
((x y) (min&max a b)))
(format #t "x: ~s\ny: ~s\n" x y)))
(let ((a 3)
(b 4))
(let*-values (((a b) (min&max 0 100))
((x y) (min&max a b)))
(format #t "x: ~s\ny: ~s\n" x y)))
(values-ref (min&max 0 3 -1) 1)
(values 1 2 3 4)
| false |
fa8618717d388a33c7f6f5e925475d8d11d4ac81
|
e5b2478b8cd1d86152b404488faea88872d4be35
|
/3.2.5.ss
|
16ed49bdc0300d46ce8651825ed1192896e82c59
|
[] |
no_license
|
xiaq/tspl4-ans
|
e6d7dde3148b086c623140c1c74e8937653cf296
|
da0f4cb56d0da63d57a739e4c8a578eee650d8ca
|
refs/heads/master
| 2020-04-03T06:25:14.087276 | 2018-11-03T18:49:01 | 2018-11-03T18:49:01 | 155,074,083 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 222 |
ss
|
3.2.5.ss
|
(define-syntax my-let
(syntax-rules ()
[(_ ([x e] ...) b1 b2 ...)
((lambda (x ...) b1 b2 ...) e ...)]
[(_ name ([x e] ...) b1 b2 ...)
(letrec [(name (lambda (x ...) b1 b2 ...))]
(name e ...))]))
| true |
d42baa45ddd8f9dd35adfc72782057477835440a
|
7cc14e6ab8e064fa967251e3249863e2cfbcc920
|
/chapter-1/check-prime.scm
|
095d8cf25f426903807213192ca7aa2d824aa2da
|
[] |
no_license
|
xueeinstein/sicp-code
|
0bec79419286705f58175067d474169afd6ba5fe
|
49602b0b13cb9c338b6af089f989c17890ba6085
|
refs/heads/master
| 2021-01-10T01:20:03.089038 | 2015-11-24T03:25:54 | 2015-11-24T03:25:54 | 43,536,317 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,999 |
scm
|
check-prime.scm
|
;;; Bill Xue
;;; 2015-10-04
;;; Check prime
;; Method I: find smallest divisor between 1 and sqrt(N)
;; O(sqrt(N))
(define (prime-by-divisor? n)
; find smallest divisor
(define (smallest-divisor)
(find-divisor 2))
(define (find-divisor test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor (+ test-divisor 1)))))
; supplementary function
(define (square x)
(* x x))
(define (divides? a b)
(= (remainder b a) 0))
; main
(= n (smallest-divisor)))
;; Method II: Fermat's little theorem (Fermat test)
;; O(logN)
;; Attention: some special numbers, i.e. Carmichael number
;; can pass Fermat test, but they are not prime
(define (prime-Fermat-test? n)
; compute base^exp % m
; xy % m = ( (x % m) * (y % m) ) % m
(define (expmod base exp m)
(cond ((= exp 0) 1)
((even? exp)
; a^b % m = (a^(b/2) % m)^2 % m
(remainder (square (expmod base (/ exp 2) m))
m))
(else
; a^b % m = (a * (a^(b-1) % m) ) % m
(remainder (* base (expmod base (- exp 1) m))
m))))
; Fermat test
; get a random number between 1 and n-1
; check (expmod a n n) = a or not
(define (fermat-test)
(define (try-it a)
(= (expmod a n n) a))
(try-it (+ 1 (random (- n 1)))))
; fast prime checker
(define (fast-prime? times)
(cond ((= times 0) #t)
((fermat-test) (fast-prime? (- times 1)))
(else #f)))
; supplementary functions
(define (square x)
(* x x))
; main
; default check times is 10
(fast-prime? 10))
;; Method III: Miller-Rabin Test
;; Attention: No Carmichael number error
;; exercise 1.28
(define (prime-Miller-Rabin-test? n)
; compute base^exp % m
; updated with un-normal square-root check
; xy % m = ( (x % m) * (y % m) ) % m
(define (expmod base exp m)
(cond ((= exp 0) 1)
((even? exp)
(let ((square-root (expmod base (/ exp 2) m)))
(if (is-normal-square-root? square-root m)
0 ; 0 represents fail signal
(remainder (square square-root) m))))
(else
(remainder (* base (expmod base (- exp 1) m))
m))))
(define (is-normal-square-root? x n)
(and (not (= x 1)) ; x != 1
(not (= x (- n 1))) ; x != n-1
(= (remainder (square x) n) 1))) ; x^2 % n = 1
; Miller-Rabin test
; get a random number between 1 and n-1
; check expmod(a (n-1) n) = 1 or not
(define (Miller-Rabin-test)
(define (try-it a)
(= (expmod a (- n 1) n) 1))
(try-it (+ 1 (random (- n 1)))))
; fast prime checker
(define (fast-prime? times)
(cond ((= times 0) #t)
((Miller-Rabin-test) (fast-prime? (- times 1)))
(else #f)))
; supplementary functions
(define (square x)
(* x x))
; main
; default check times is 10
(fast-prime? 10))
| false |
e24dc3b83269b9843d796972d3ccfa0de763398d
|
ece1c4300b543df96cd22f63f55c09143989549c
|
/Chapter4/Exercise4.31.scm
|
eed2113253ea469483d09e36a130d8ea26ded002
|
[] |
no_license
|
candlc/SICP
|
e23a38359bdb9f43d30715345fca4cb83a545267
|
1c6cbf5ecf6397eaeb990738a938d48c193af1bb
|
refs/heads/master
| 2022-03-04T02:55:33.594888 | 2019-11-04T09:11:34 | 2019-11-04T09:11:34 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,435 |
scm
|
Exercise4.31.scm
|
; Exercise 4.31: The approach taken in this section is somewhat unpleasant, because it makes an incompatible change to Scheme. It might be nicer to implement lazy evaluation as an upward-compatible extension, that is, so that ordinary Scheme programs will work as before. We can do this by extending the syntax of procedure declarations to let the user control whether or not arguments are to be delayed. While we’re at it, we may as well also give the user the choice between delaying with and without memoization. For example, the definition
; (define (f a (b lazy) c (d lazy-memo))
; ...)
; would define f to be a procedure of four arguments, where the first and third arguments are evaluated when the procedure is called, the second argument is delayed, and the fourth argument is both delayed and memoized. Thus, ordinary procedure definitions will produce the same behavior as ordinary Scheme, while adding the lazy-memo declaration to each parameter of every compound procedure will produce the behavior of the lazy evaluator defined in this section. Design and implement the changes required to produce such an extension to Scheme. You will have to implement new syntax procedures to handle the new syntax for define. You must also arrange for eval or apply to determine when arguments are to be delayed, and to force or delay arguments accordingly, and you must arrange for forcing to memoize or not, as appropriate.
(load "/Users/soulomoon/git/SICP/Chapter4/lazyeval.scm")
(define (eval-definition exp env)
(define-variable! (definition-variable exp)
(eval# (definition-value exp) env)
env)
'ok)
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caadr exp)))
(define (definition-value exp)
(if (symbol? (cadr exp))
(caddr exp)
(make-lambda (cdadr exp) ; formal parameters
(cddr exp)))) ; body
(define (apply# procedure arguments env)
; (display "new")(display procedure)
(cond ((primitive-procedure? procedure)
(display "apply#--------------------")(display procedure)(display arguments)(newline )
(apply-primitive-procedure
procedure
(list-of-arg-values
arguments
env))) ; changed
((compound-procedure? procedure)
; (display (procedure-body procedure))
(eval-sequence
(procedure-body procedure)
(extend-environment
(matching-paras
(procedure-parameters procedure)
arguments
env)
(matching-args
(procedure-parameters procedure)
arguments
env) ; changed
(procedure-environment procedure))))
(else (error "Unknown procedure
type: APPLY"
procedure))))
(define (matching-paras paras args env)
(map (lambda (p a)
(cond
((symbol? p) p)
(else (car p))))
paras args))
(define (matching-args paras args env)
(map (lambda (p a)
(cond
((symbol? p) a)
(else
(if (or (eq? (cadr p) 'lazy-memo) (eq? (cadr p) 'lazy))
(cons (cadr p) (delay-it a env))
(error "wrong variable suffix" (cadr p))))))
paras args))
(define (actual-value exp env)
(force-selector (eval# exp env)))
(define (force-selector exp)
(cond
((lazy? exp) (force-it-without-memo (cdr exp)))
((lazy-memo? exp) (force-it (cdr exp)))
(else (force-it exp))
)
)
(define (lazy? obj) (tagged-list? obj 'lazy))
(define (lazy-memo? obj) (tagged-list? obj 'lazy-memo))
(interpret
'(begin
(define (p1 (x lazy))
(set! x (cons x '(2))) x)
(display (p1 1))
)
)
; Welcome to DrRacket, version 6.7 [3m].
; Language: SICP (PLaneT 1.18); memory limit: 128 MB.
; eval#-----(begin (define (p1 (x lazy)) (set! x (cons x '(2))) x) (display (p1 1)))
; eval#-----(define (p1 (x lazy)) (set! x (cons x '(2))) x)
; eval#-----(lambda ((x lazy)) (set! x (cons x '(2))) x)
; eval#-----(display (p1 1))
; eval#-----display
; apply#--------------------(primitive #<procedure:mdisplay>)((p1 1))
; eval#-----(p1 1)
; eval#-----p1
; delay-it--------1
; eval#-----(set! x (cons x '(2)))
; eval#-----(cons x '(2))
; eval#-----cons
; apply#--------------------(primitive #<procedure:mcons>)(x '(2))
; eval#-----x
; eval#-----1
; eval#-----'(2)
; eval#-----x
; (1 2)
; >
| false |
c4082316f12b363c84d05b75455d6428c8e33fde
|
404313517ba0846313af5226e05d9092d99a38b3
|
/Scheme/Theory/abstract-data-structures.scm
|
a6d7fde738a1f7f8c5a4c4dfce729528adf11d01
|
[] |
no_license
|
georgistoilov8/Functional-Programming
|
00fab1d97a1ea66d0e63c55ed9ead5d309118514
|
38837b571c7e8b4ecef462d85e2ae47b316050f7
|
refs/heads/master
| 2020-08-29T00:39:31.773279 | 2020-01-12T17:00:31 | 2020-01-12T17:00:31 | 217,867,904 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,512 |
scm
|
abstract-data-structures.scm
|
#lang racket
;;; Абстракция със структури от данни
;; Рационално число
; Базови операции
;(define (make-rat n d) (cons n d))
;(define make-rat cons)
;(define (get-numer r) (car r))
;(define get-numer car)
;(define (get-denom r) (cdr r))
;(define get-denom cdr)
; По-добре:
(define (make-rat2 n d)
(if (= d 0) (cons n 1) (cons n d)))
; Още по-добре. Работим с нормализирани дроби
; Дефинирана по-надолу по още един начин
#|(define (make-rat n d)
(if (or (= d 0) (= n 0)) (cons 0 1)
(let* ( (g (gcd n d))
(ng (quotient n g))
(dg (quotient d g)))
(if (> dg 0) (cons ng dg)
(cons (- ng) (- dg))))))
|#
; Аритметични операции
; Умножение на рационални числа
(define (*rat r1 r2) (make-rat (* (get-numer r1) (get-numer r2))
(* (get-denom r1) (get-denom r2))))
;(*rat (make-rat2 1 2) (make-rat2 2 3))
; Събиране на рационални числа
(define (+rat p q) (make-rat
(+ (* (get-numer p) (get-denom q))
(* (get-denom p) (get-numer q)))
(* (get-denom p) (get-denom q))))
;(+rat (make-rat2 1 2) (make-rat2 2 3))
; Сравнение на рационални числа
(define (<rat p q)
(< (* (get-numer p) (get-denom q))
(* (get-numer q) (get-denom p))))
;(<rat (make-rat2 1 2) (make-rat2 2 3))
;;; Програми с рационални числа
; Намиране на експонента
(define (pow x n)
(cond ( (= n 0) 1)
( (< n 0) (/ 1 (pow x (- n))))
( else (* x (pow x (- n 1))))))
(define (fact x)
(if (= x 0) 1
(* x (fact (- x 1)))))
(define (accumulate op nv a b term next)
(if (> a b) nv
(op (term a) (accumulate op nv (next a) b term next))))
(define (my-exp x n)
(accumulate +rat (make-rat 0 1) 0 n (lambda (i) (make-rat (pow x i) (fact i))) (lambda (x) (+ x 1))))
;;; До тук не може да се различи сигнатурата на структурата. Освен рационални числа,
;;; с две числа се представя точка в пространството, комплексно число и т.н.
;<-------------------------------
; Нека добавим етикет на обекта
#|(define (make-rat n d)
(cons 'rat
(if (or (= d 0) (= n 0)) (cons 0 1)
(let* ( (g (gcd n d))
(ng (quotient n g))
(dg (quotient d g)))
(if (> dg 0) (cons ng dg)
(cons (- ng) (- dg)))))))
|#
;(define get-numer cadr)
;(define get-denom cddr)
; Вече може да се направи проверка дали даден обект е рационално число
(define (rat? p)
(and (pair? p) (eqv? (car p) 'rat)
(pair? (cdr p))
(integer? (cadr p)) (positive? (cddr p))
(= (gcd (cadr p) (cddr p)) 1)))
; Можем да добавим проверка за коректност:
(define (check-rat f)
(lambda (p)
(if (rat? p) (f p) 'error)))
(define get-numer (check-rat cadr))
(define get-denom (check-rat cddr))
;------------------------------------------>
;<------------------------------------------
; Операциите над структурата от данни са видими глобално, но можем да ги направим 'private'
(define (make-rat n d)
(let* ((g (gcd n d))
(numer (quotient n g))
(denom (quotient d g)))
(lambda (prop . params)
(case prop
('get-numer numer)
('get-denom denom)
('print (cons numer denom))
('* (let ((r (car params)))
(make-rat (* numer (r 'get-numer))
(* denom (r 'get-denom)))))
(else 'unknown-prop)))))
;(define r (make-rat 4 6); (r 'print) -> (2 . 3)
;(define r1 (make-rat 3 5)); (define r2 (make-rat 5 2)); ((r1 '* r2) 'print) -> '(3 . 2)
#|
(define (make-rat n d)
(let* ((g (gcd n d))
(numer (quotient n g))
(denom (quotient d g)))
(define (self prop . params)
(case prop
('get-numer numer)
('get-denom denom)
('print (cons numer denom))
('* (let ((r (car params)))
(make-rat (* numer (self 'get-numer))
(* denom (self 'get-denom)))))
(else 'unknown-prop)))
self))
|#
| false |
c1e53c28d2589c9bbd057df3c3a8c4c2c43e88be
|
7b0df9640ae1b8e1172f0f90c5428b0802df8ed6
|
/rest-dab.scm
|
0af0ff60380441c7f361f3c5c86c1dc2e8b7c121
|
[] |
no_license
|
erosness/sm-server
|
5954edfc441e773c605d2ac66df60bb983be01a3
|
cc302551e19f6d2b889a41ec28801004b0b28446
|
refs/heads/master
| 2020-08-31T13:23:03.670076 | 2016-02-18T19:10:55 | 2016-02-18T19:10:55 | 218,699,588 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,269 |
scm
|
rest-dab.scm
|
(use restlib dab matchable looper clojurian-syntax)
(import turi)
(handle-exceptions
e (pp e)
)
(define-handler /v1/catalog/dab
(lambda () `((preload . #( ((title . "Radio Stations") (uri . "/catalog/dab/stations")))))))
(define (dab-abort-if-scanning)
(if dab-scanning?
(response-unavailable)))
(define (ensure-dab-on)
(dab-abort-if-scanning)
(if (not (dab-on?)) (dab-turn-on)))
;; find channel in (dab-channels) and return its fixnum index. or
;; error if not found.
(define (find-dab-index channel)
(car (or (find (lambda (pair) (equal? channel (cdr pair))) (dab-channels))
(error (conc "channel not found in " (dab-channels)) channel))))
;; dab's t2s is like a normal alsa capture, but changes the frequence
;; of the DAB module before sending the stream url.
(define-turi-adapter channel->turi "dab"
(lambda (params)
(let* ((chidxstr (alist-ref 'ch params))
(chidx (find-dab-index chidxstr)))
(pp `(rest-dab station ,chidx))
(ensure-dab-on)
(match (dab-command (dab.sl.station chidx))
('(item-set-response FS_OK)
;; TODO: find IP so zones can reach DAB
`((url . "default:CARD=imxaudiovenice9")
(format . "alsa")))
(anything (error (conc "cannot set channel " chidxstr) anything))))))
(define-handler /v1/catalog/dab/stations
(pagize
(lambda ()
(dab-abort-if-scanning)
(map (lambda (idx.name)
(let* ((channel (cdr idx.name))
(index (car idx.name))
(turi (channel->turi `((ch . ,channel)))))
`((title . ,channel)
(turi . ,turi)
(type . "dab"))))
(dab-channels)))))
;; start querying for stations. dab-channels is filled from dab-read-thread.
(define dab-scanning? #f)
(begin
(handle-exceptions e (void) (thread-terminate! dab-channels-thread))
;; (thread-state dab-channels-thread)
(define dab-channels-thread
(thread-start!
(->> (lambda ()
;; initialize dab
(dab-turn-on) ;; turn on the actual radio module
(dab-command (audio.attenuation 0)) ;; turn off mute default
;; delete channels from previous search
(dab-command (dab.sl.factoryReset 'reset))
(dynamic-wind
(lambda () (set! dab-scanning? #t))
(lambda () (dab-refresh-channels!))
(lambda () (set! dab-scanning? #f)))
#f) ;; <-- exit thread on successful completion
(loop/exceptions (lambda (e) (pp `(error DAB channels ,(condition->list e) )) #t))
(loop/interval 60)
(loop)))))
;; helper utils. TODO: allow us to output pretty HTML here with a meta
;; refresh tag!
(define-handler /v1/catalog/dab/debug
(lambda ()
`((tuneStatus . ,(symbol->string (parse-dab.tuneStatus (dab-command (dab.tuneStatus)))))
(dab.scan.state . , (symbol->string (parse-dab.scan.state (dab-command (dab.scan.state)))))
(dab.sl.station . , (parse-dab.sl.station))
(audio.sampleRate . ,(conc (dab-command (audio.sampleRate)))))))
(define-handler /v1/catalog/dab/buzzer
(lambda ()
(dab-reset)
(dab-command (audio.buzzer.state 'on))
(dab-command (audio.buzzer.frequency 440))))
| false |
a01044696d9813762ec12254254e3795ac536a7d
|
9998f6f6940dc91a99e0e2acb4bc4e918f49eef0
|
/src/android/android-packager.ss
|
5f1d4a24f77361e8a782c7034662837588460410
|
[] |
no_license
|
JessamynT/wescheme-compiler2012
|
326d66df382f3d2acbc2bbf70fdc6b6549beb514
|
a8587f9d316b3cb66d8a01bab3cf16f415d039e5
|
refs/heads/master
| 2020-05-30T07:16:45.185272 | 2016-03-19T07:14:34 | 2016-03-19T07:14:34 | 70,086,162 | 0 | 0 | null | 2016-10-05T18:09:51 | 2016-10-05T18:09:51 | null |
UTF-8
|
Scheme
| false | false | 983 |
ss
|
android-packager.ss
|
#lang scheme/base
(require scheme/contract
(prefix-in local: "local-android-packager.ss")
(prefix-in remote: "server-side-packager/client-side-packager.ss")
"../config.ss"
"../program-resources.ss")
;; local-android-ready?: -> boolean
;; Produces true if we can do local android packaging.
(define (local-android-ready?)
(and (file-exists? (current-ant-bin-path))
(directory-exists? (current-android-sdk-path))))
;; build-android-package: string program/resources -> bytes
;; Either tries to use the local android packager; if the resources aren't available,
;; then tries to use the web service.
(define (build-android-package program-name program/resources)
(cond
[(local-android-ready?)
(local:build-android-package program-name program/resources)]
[else
(remote:build-android-package program-name program/resources)]))
(provide/contract
[build-android-package (string? program/resources? . -> . bytes?)])
| false |
9d837c463eadbfcfd24543753c02e4ac855ecf20
|
00466b7744f0fa2fb42e76658d04387f3aa839d8
|
/sicp/chapter2/2.2/ex2.29.scm
|
da1a031736f2f34d389904c63d8903c0aa45ad07
|
[
"WTFPL"
] |
permissive
|
najeex/stolzen
|
961da2b408bcead7850c922f675888b480f2df9d
|
bb13d0a7deea53b65253bb4b61aaf2abe4467f0d
|
refs/heads/master
| 2020-09-11T11:00:28.072686 | 2015-10-22T21:35:29 | 2015-10-22T21:35:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,390 |
scm
|
ex2.29.scm
|
#lang scheme
; 2.29
(define (make-mobile left right)
(list left right)
)
(define (make-branch length structure)
(list length structure)
)
(define (branch-left mobile)
(car mobile)
)
(define (branch-right mobile)
(car (cdr mobile))
)
(define (branch-length branch)
(car branch)
)
(define (branch-structure branch)
(car (cdr branch))
)
(define branch1 (make-branch 1 10))
(define branch2 (make-branch 1 20))
(define mobile1 (make-mobile branch1 branch2))
(define branch3 (make-branch 2 mobile1))
(branch-length branch1)
(branch-structure branch1)
(branch-structure branch3)
(define (total-weight branch)
(let
((structure (branch-structure branch)))
(if (pair? structure)
(+ (total-weight (branch-left structure))
(total-weight (branch-right structure)))
structure
)
)
)
(total-weight branch3)
(define (torque branch)
(let
((len (branch-length branch))
(weight (total-weight branch)))
(* len weight)
)
)
(define (balanced? mobile)
(= (torque (branch-left mobile))
(torque (branch-right mobile)))
)
(balanced? mobile1)
(define branch5 (make-branch 10 10))
(define branch6 (make-branch 10 10))
(balanced? (make-mobile branch5 branch6))
; d - change only selectors
| false |
7e6441aeebd6b44ae663421739f4f7de481928b7
|
1384f71796ddb9d11c34c6d988c09a442b2fc8b2
|
/scheme/genipc/stage-1.scm
|
af8e0e1edb8cb54374e0f87d7beb99288ffac10a
|
[] |
no_license
|
ft/xmms2-guile
|
94c2479eec427a370603425fc9e757611a796254
|
29670e586bf440c20366478462f425d5252b953c
|
refs/heads/master
| 2021-07-08T07:58:15.066996 | 2020-10-12T01:24:04 | 2020-10-12T01:24:04 | 74,858,831 | 1 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,466 |
scm
|
stage-1.scm
|
;; Copyright (c) 2017 xmms2-guile workers, All rights reserved.
;;
;; Terms for redistribution and use can be found in doc/LICENCE.
(define-module (genipc stage-1)
#:use-module (ice-9 optargs)
#:use-module (sxml match)
#:use-module (genipc utilities)
#:export (sxml->sexp))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Stage 1: Destructure SXML into s-expressions. This massages the data from
;; XML into something that the following stages can work with easier. This also
;; does most of the name adjustments (it really should to all of them). This
;; stage makes heavy use of ‘sxml-match’.
(define (handle-unknown-xml name data)
(notify "~a: Cannot handle XML entry: ~a~%" name data))
(define (type->sexp type)
;;(notify "type: ~a~%" type)
(sxml-match type
((xmms::binary) '(binary))
((xmms::collection) '(collection))
((xmms::int) '(integer))
((xmms::string) '(string))
((xmms::unknown) '(unknown))
((xmms::list ,rest ...) `((list ,@(am type->sexp rest))))
((xmms::dictionary ,rest ...) `((dictionary ,@(am type->sexp rest))))
((xmms::enum-value (@ (name ,n))) `((enumeration ,(adjust-name/enum n))))
(,otherwise (begin (handle-unknown-xml 'type->sexp otherwise)
(list type)))))
(define (method-arg->sexp arg)
;;(notify "arg: ~a~%" arg)
(sxml-match arg
((xmms::name ,name) `((name ,(adjust-name/arg name))))
((xmms::type ,type) `((type ,@(type->sexp type))))
((xmms::documentation ,doc) `((documentation ,(cleanup-documentation doc))))
((xmms::default-hint ,hint) `((default-hint ,hint)))
(,otherwise (begin (handle-unknown-xml 'method-arg->sexp otherwise)
(list arg)))))
(define (return-value->sexp return-value)
;;(notify "return-value: ~a~%" return-value)
(sxml-match return-value
((xmms::type ,type) `((type ,@(type->sexp type))))
((xmms::documentation ,doc) `((documentation ,(cleanup-documentation doc))))
(,otherwise (begin (handle-unknown-xml 'return-value->sexp otherwise)
(list return-value)))))
(define (method->sexp method)
;;(notify "method: ~a~%" method)
(sxml-match method
((xmms::name ,name) `((name ,(adjust-name/method name))))
((xmms::documentation ,doc) `((documentation ,(cleanup-documentation doc))))
((xmms::argument ,rest ...) `((argument ,@(am method-arg->sexp rest))))
((xmms::return_value ,rest ...) `((return-value
,@(am return-value->sexp rest))))
(,otherwise (begin (handle-unknown-xml 'method->sexp otherwise)
(list method)))))
(define (broadcast-or-signal->sexp bs)
;;(notify "bs: ~a~%" bs)
(sxml-match bs
((xmms::id ,id) `((identifier ,(string->number id))))
((xmms::name ,name) `((name ,(adjust-name/b-or-s name))))
((xmms::documentation ,doc) `((documentation ,(cleanup-documentation doc))))
((xmms::return_value ,rest ...) `((return-value
,@(am return-value->sexp rest))))
(,otherwise (begin (handle-unknown-xml 'broadcast-or-signal->sexp otherwise)
(list bs)))))
(define (enum->sexp elst)
;;(notify "elst: ~a~%" elst)
(sxml-match elst
((xmms::name ,name) `((name ,(adjust-name/enum name))))
((xmms::member (@ . ,attr) ,member) (if (null? attr)
`((member ,(adjust-name/member member)))
`((member ,attr ,(adjust-name/member member)))))
((xmms::namespace-hint ,nsh)
`((namespace-hint ,(adjust-name/namespace-hint nsh))))
(,otherwise (begin (handle-unknown-xml 'enum->sexp otherwise)
(list elst)))))
(define (transform-value type value)
(let* ((transformers `((integer . ,string->number)))
(type (if (string? type)
(string->symbol type)
type))
(transformer* (assq-ref transformers type))
(transformer (or transformer* (lambda (x)
(notify "transform-value: Unknown type: ~a (~a)~%"
type x)
x))))
(transformer value)))
(define (constant->sexp clst)
;;(notify "clst: ~a~%" clst)
(sxml-match clst
((xmms::name ,name) `((name ,(adjust-name/constant name))))
((xmms::value (@ (type ,t)) ,v) (list `(value ,(transform-value t v))))
(,otherwise (begin (handle-unknown-xml 'enum->sexp otherwise)
(list clst)))))
(define (sxml->sexp tree)
;;(notify "tree: ~a~%" tree)
(sxml-match tree
((*TOP* (*PI* ,stuff ...) ,things ...)
`(xmms2-ipc-description ,@(am sxml->sexp things)))
((xmms::ipc (@ (version ,v)) ,objs ...) `((version ,v) ,@(am sxml->sexp objs)))
((xmms::object (xmms::name ,name) ,things ...)
`((object (name ,(adjust-name/object name)) ,@(am sxml->sexp things))))
((xmms::method ,rest ...) `((method ,@(am method->sexp rest))))
((xmms::broadcast ,rest ...) `((broadcast ,@(am broadcast-or-signal->sexp rest))))
((xmms::signal ,rest ...) `((signal ,@(am broadcast-or-signal->sexp rest))))
((xmms::enum ,rest ...) `((enum ,@(am enum->sexp rest))))
((xmms::constant ,rest ...) `((constant ,@(am constant->sexp rest))))
(,otherwise (begin (handle-unknown-xml 'sxml->sexp otherwise)
(list tree)))))
| false |
a0cb7fb512781505d720f3781cd6fdd25cb45848
|
3c3e79da5fa173750dd941c4bb94c71de8ee9c2d
|
/s9/ext/sys-plan9/webfs.scm
|
c10b3459e4b61e324a06633eefdc46065a9e9642
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] |
permissive
|
smazga/m9scm
|
2b9d6f1f4d44e7e1f14dbb206db686044f8be88a
|
7da5f719654951d255942dfa210ac4176f66e1bc
|
refs/heads/master
| 2022-11-22T13:39:36.111041 | 2020-07-10T19:53:04 | 2020-07-10T19:53:04 | 278,719,406 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,879 |
scm
|
webfs.scm
|
(require-extension sys-plan9)
(define *debug* #t)
(define (debug msg) (if *debug* (format #t "~A~%" msg) #f))
(define *useragent* "useragent 's9fes webfs/0.1 (compatible; nope)'")
(define-structure webfs
(path "") (ctl "") (payload '()) (cookies '()) (stop '()))
(define (create-webfs url)
(let* ((id (car (read-file (open-input-file "/mnt/web/clone"))))
(path (string-append "/mnt/web/" id "/"))
(ctl (string-append path "ctl"))
(session
(make-webfs path ctl '()
(sys:open ctl sys:OREAD) ; simply to keep the connection active
)))
(webfs:set-url session url)
session
))
; not finished
(define (webfs:add-creds creds)
(if (null? creds) #f #t))
(define (webfs:ctl-write w msg)
(let ((ctl (sys:open (webfs-ctl w) sys:OWRITE)))
(debug (format #f "ctl: ~A" msg))
(sys:write ctl msg)
(sys:close ctl)))
(define (webfs:ctl-read w)
(read-file (open-input-file (webfs-ctl w))))
(define (webfs:path-write w dir msg)
(let ((path
(sys:open (string-append (webfs-path w) dir) sys:OWRITE)))
(sys:write path msg)
(sys:close path)))
(define (webfs:path-read w dir)
(read-file (open-input-file (string-append (webfs-path w) dir))))
(define (webfs:set-url w url)
(debug (format #f "setting url: ~A" url))
(webfs:ctl-write w (string-append "url " url)))
(define (webfs:url w)
(car
(read-file
(open-input-file
(string-append (webfs-path w) "parsed/url")))))
(define (webfs:host w)
(car
(read-file
(open-input-file
(string-append (webfs-path w) "parsed/host")))))
(define (webfs:scheme w)
(car
(read-file
(open-input-file
(string-append (webfs-path w) "parsed/scheme")))))
(define (webfs:path w)
(car
(read-file
(open-input-file
(string-append (webfs-path w) "parsed/path")))))
(define (webfs:get w url)
(let ()
(webfs:set-url w url)
(webfs:body w)))
(define (webfs:post w url body creds)
(let ()
(webfs:ctl-write w (string-append "url " url))
(with-output-to-file (string-append (webfs-path w) "postbody")
(lambda () (write body)))
(webfs:body w)))
; with-input-from-file doesn't seem to work for this for some reason
(define (webfs:body w)
(debug "reading...")
(let* ((bpath (string-append (webfs-path w) "body"))
(bhandle (sys:open bpath sys:OREAD)))
(let loop ((str "")
(b (sys:read bhandle 1024)))
(if (eof-object? b) str
(loop (string-append str b) (sys:read bhandle 1024))))))
;; ======= http code =======
(define (http:new-session url)
(create-webfs url))
(define (http:set-url session url)
(webfs:ctl-write session (string-append "url " url)))
(define (http:set-cookies session cookies) '())
(define (http:get-cookies session)
(let* ((f (sys:open "/mnt/webcookies/http" sys:ORDWR))
(scheme (webfs:scheme session))
(host (webfs:host session))
(url (string-append scheme "://" host))
(cookies ""))
(debug (format #f "cookies read url: ~A" url))
(sys:write f url)
(set! cookies (sys:read f 4096))
(debug (format #f "cookies: ~A" cookies))
(sys:close f)
cookies
))
(define (http:get url . options)
(let ((w (create-webfs url)))
(webfs:ctl-write w *useragent*)
(webfs:get w url)))
(define (http:perform session)
(if (null? (webfs-payload session))
(webfs:body session)
(webfs:post session)))
(define (http:post url body . creds)
(let ((w (create-webfs url)))
(webfs:ctl-write w *useragent*)
(webfs:post w url body creds)))
(define (http:insecure session) '())
(define (http:user:pass session user pass)
(let ((scheme (webfs:scheme session))
(host (webfs:host session))
(path (webfs:path session)))
(webfs:set-url session (format #f "~A://~A:~A@~A~A"
scheme user pass host path))))
(define (http:basic-auth session) '())
(define (http:set-headers session headers)
(for-each
(lambda (h)
(webfs:ctl-write session (format #f "headers ~A" h))
(vector->list headers))))
| false |
8898f15de095d07eb9a6c270c67de1659b328680
|
4e2bb57118132e64e450671470c132205457d937
|
/weinholt/compression/lzma2.sls
|
b795614960b08cd6ddaa11fc1ffbe70fb6f89b00
|
[
"MIT"
] |
permissive
|
theschemer/industria
|
8c4d01d018c885c0437e2575787ec987d800514f
|
9c9e8c2b44280d3b6bda72154a5b48461aa2aba5
|
refs/heads/master
| 2021-08-31T23:32:29.440167 | 2017-12-01T23:24:01 | 2017-12-01T23:24:01 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,932 |
sls
|
lzma2.sls
|
;; -*- mode: scheme; coding: utf-8 -*-
;; Copyright © 2011, 2012 Göran Weinholt <[email protected]>
;; Permission is hereby granted, free of charge, to any person obtaining a
;; copy of this software and associated documentation files (the "Software"),
;; to deal in the Software without restriction, including without limitation
;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;; and/or sell copies of the Software, and to permit persons to whom the
;; Software is furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;; DEALINGS IN THE SOFTWARE.
#!r6rs
;; Decoder for LZMA2, a layer above LZMA.
#|
A chunk can be at most this large when uncompressed:
(let ((usize* #xFFFF) (ctrl #xFF))
(fx+ (fxior usize* (fxarithmetic-shift-left (fxbit-field ctrl 0 5) 16))
1)) => 2097152
|#
(library (weinholt compression lzma2)
(export lzma2-decode-chunk)
(import (rnrs)
(weinholt compression lzma)
(weinholt compression sliding-buffer)
(weinholt struct pack))
(define-syntax trace
(syntax-rules ()
#;
((_ . args)
(begin
(for-each display (list . args))
(newline)))
((_ . args) (begin 'dummy))))
;; Decodes one LZMA2 chunk. Returns a new state. If there's no more
;; data in the LZMA2 block then the end-of-file object is returnred.
(define (lzma2-decode-chunk p sink dictionary-size state)
(define who 'lzma2-decode-chunk)
(define fxasl fxarithmetic-shift-left)
(define (decode-props b)
(let* ((pb (fxdiv b (* 9 5)))
(prop (fx- b (fx* pb (* 9 5))))
(lp (fxdiv prop 9))
(lc (fx- prop (fx* lp 9))))
(trace "LZMA2: Literal context bits (lc): " lc ;[0,8]
", Literal position bits (lp): " lp ;[0,4]
", Position bits (pb): " pb) ;[0,4]
(values lc lp pb)))
(define (get-props p)
(trace "LZMA2: reading new properties")
(let ((b (get-u8 p)))
(when (fx>? b (+ (* (+ (* 4 5) 4)
9)
8))
(error who "Bad properties for LZMA2 chunk" p))
b))
(define (fresh-dictionary)
(trace "LZMA2: dictionary reset")
(make-sliding-buffer sink dictionary-size))
(define (return-state dictionary props lzma-state position)
(vector dictionary props lzma-state position))
(define (empty-state)
(vector #f #f #f 0))
(let ((state (or state (empty-state))))
(let ((dictionary (vector-ref state 0))
(props (vector-ref state 1))
(lzma-state (vector-ref state 2))
(position (vector-ref state 3)))
(let ((ctrl (get-u8 p)))
(trace "LZMA2 control: #x" (number->string ctrl 16))
(case ctrl
((#x00) (eof-object)) ;end of block
((#x01 #x02) ;uncompressed chunk
(let ((dictionary (if (= ctrl #x01)
(fresh-dictionary)
dictionary)))
(let ((csize (fx+ (get-unpack p "!S") 1)))
(trace "Uncompressed chunk: " csize)
(sliding-buffer-read! dictionary p csize)
(sliding-buffer-drain! dictionary)
(return-state dictionary props lzma-state (+ position csize)))))
(else
(let-values (((usize* csize*) (get-unpack p "!SS")))
(let ((usize (fx+ (fxior usize* (fxasl (fxbit-field ctrl 0 5) 16))
1))
(csize (fx+ csize* 1))
(cmd (fxand ctrl #xE0)))
(trace "Uncompressed size: " usize " Compressed size: " csize)
;; The control codes are instructions to reset the
;; dictionary, to read new properties, or to reset
;; the decoder state.
(case cmd
((#x80 #xA0 #xC0 #xE0)
(let ((dictionary (if (memv cmd '(#xE0))
(fresh-dictionary)
dictionary))
(props (if (memv cmd '(#xC0 #xE0))
(get-props p)
props)))
(let*-values (((lc lp pb) (decode-props props)))
(let ((lzma-state*
(cond ((and lzma-state
(not (memv cmd '(#xA0 #xC0 #xE0))))
(trace "LZMA: reuse old decoder state")
(lzma-state dictionary usize lc lp pb))
(else
(trace "LZMA2: reset decoder state")
(lzma-decode-chunk p dictionary usize
lc lp pb position)))))
(trace "LZMA2: chunk decoded")
(sliding-buffer-drain! dictionary)
(return-state dictionary props lzma-state*
(+ position usize))))))
(else
(error who "Invalid control code" ctrl))))))))))))
| true |
aa1a4bc2fae72b9e3d09ed99a6f5de45803d64b1
|
5c90b20606ccbd30c23988c26a0b64a0243a8ad2
|
/module/mlg/math.scm
|
89819962edd84d2a566bef6ef516ba187e1b5150
|
[] |
no_license
|
spk121/mlg-lib
|
a670ac95e4a3210f7de5fd4d702d4bf2d0ed6ad8
|
09239a0a126d47aaccf624b7983202f69152aa40
|
refs/heads/master
| 2021-06-01T18:26:37.192030 | 2020-01-08T19:47:34 | 2020-01-08T19:47:34 | 1,869,125 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 18,177 |
scm
|
math.scm
|
;;; -*- mode: scheme; coding: utf-8; indent-tabs-mode: nil; -*-
;;; (mlg math) - some math and math-like procedures
;;; Copyright (C) 2017 Michael L. Gran <[email protected]>
;;;
;;; This program is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License as
;;; published by the Free Software Foundataion, either version 3 of
;;; this License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see
;;; <http://www.gnu.org/licenses/>
(define-module (mlg math)
#:use-module (srfi srfi-1)
#:export (
add-num-or-false
array-absolute-sum-of-slice
array-rotate-slice-pairs!
array-scale-and-add-slice-to-slice!
array-scale-slice!
array-sum-product-of-slice-pairs
binomial-coefficient
cast-int32-to-uint32
cast-uint32-to-int32
cumulative-sum
dct-f64-forward-8-point
dct-f64-inverse-8-point
deal
gauss-legendre-quadrature
legendre-polynomial
lognot-uint16
lognot-uint32
lognot-uint64
lognot-uint8
make-2d-f32-array
make-2d-f32-column-vector
make-2d-f32-row-vector
transpose-2d-f32-array
monotonic-list-pos-to-coord
pythag
quadratic-roots
real->integer
;; 8.3.2 Numerical Differentiation
deriv2
deriv2F
deriv3
math-load-extension
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; helper funcs
(define (bytes-to-bits b)
(* 8 b))
(define (unsigned-limit b)
(1- (expt 2 (bytes-to-bits b))))
(define (lognot-uint x b)
(- (unsigned-limit b) (logand (unsigned-limit b) x)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
(define (add-num-or-false . vals)
"Add the parameters, returning #f if any of the parameters
is not a number."
(if (null? vals)
0
(let loop ((sum 0)
(cur (car vals))
(rest (cdr vals)))
(if (not (number? cur))
#f
;; else
(if (null? rest)
(+ cur sum)
;; else
(loop (+ cur sum)
(car rest)
(cdr rest)))))))
(define (array-absolute-sum-of-slice arr n idx)
"Given an array ARR, consider the array slice where the index of the
Nth dimension is equal to IDX. Compute the sum of the absolute values
of the entries of the slice."
(error 'not-implemented))
(define (array-rotate-slice-pairs! arr n idx1 idx2 theta)
"Given an array ARR, consider two array slices A and B where the Nth
dimension is equal to IDX1 or IDX2 respectively.
Replace each element of A with cos(theta)*A+sin(theta)*B.
Replace each element of B with -sin(theta)*A+cos(theta)*B."
(error 'not-implemented))
(define (array-scale-entry! arr scale . indices)
"Modify array ARR such that the entry at the location given
by indices is multiplied by the scale factor SCALE."
(apply array-set!
(append (list arr)
(list (* scale (apply array-ref (append (list arr) indices))))
indices)))
(define (array-scale-slice! arr dimension idx scale)
"Given an array ARR, multiply by a scale factor all the elements of
the array where the array index for dimension DIMENSION is equal to
INDEX."
(array-index-map! arr
(lambda indices
(if (= idx (list-ref indices dimension))
(* (apply array-ref (pk (append (list arr) indices))) scale)
;; else
(apply array-ref (append (list arr) indices))))))
(define (array-scale-and-add-slice-to-slice! arr n idx1 idx2 scale)
"Given an array ARR, consider two array slices, where the Nth array
index is equal to IDX1 and IDX2 respectively. For each element in the
slice at IDX1, multiply the corresponding element in the slice at IDX2
by the scale factor SCALE, and then add it to element in the slice at
IDX1."
(array-index-map! arr
(lambda indices
(if (= idx1 (list-ref indices n))
(let ((indices2 (list-copy indices)))
(list-set! indices2 n idx2)
(+
(* (apply array-ref (pk (append (list arr) indices2)))
scale)
(apply array-ref (append (list arr) indices))))
;; else
(apply array-ref (append (list arr) indices))))))
(define (array-sum-product-of-slices arr n idx1 idx2)
"Given an array ARR, consider two array slices, where the Nth
array index is equal to IDX1 and IDX2 respectively. Compute the sum
of the the products of the elements of two array slices."
;; FIXME: not implementsed
(error 'not-implemented))
(define (binomial-coefficient n k)
"Computes the binomial coefficient 'n choose k'."
(if (> k n)
0
(if (or (= k 0) (= k n))
1
;; else
(let loop ((val 1)
(n n)
(k k))
(if (= k 0)
val
;; else
(loop (* val (/ n k))
(1- n)
(1- k)))))))
(define (cast-int32-to-uint32 x)
(if (< x 0)
(- #x100000000 (logand #x7fffffff (abs x)))
(logand #x7FFFFFFF x)))
(define (cast-uint32-to-int32 x)
(if (<= x #x7fffffff)
x
(- (- #x100000000 (logand x #xffffffff)))))
(define (cumulative-sum lst)
"Given a list of numbers (x0 x1 x2 ...),
returns a list of the same length of the form
(x0 x0+x1 x0+x1+x2 ..."
(if (null? lst)
lst
;; else
(reverse
(fold (lambda (cur prev)
(append (list (+ cur (first prev))) prev))
(list (car lst))
(cdr lst)))))
;; The cosine basis function scale factors for the DCT.
(define CU_0 (/ 1.0 (sqrt 2.0)))
(define CU_N 1.0)
(define π 3.141592654)
(define (dct-f64-forward-8-point f)
"Given a uniform f64vector of 8 numbers, this procedure returns a
uniform f64vector of 8 real numbers which are the coefficients of an
8-point discrete cosine transform."
(let ((F (make-f64vector 8 0.0)))
(do ((μ 0 (1+ μ))) ((>= μ 8))
(let ((coef (if (zero? μ)
(* 0.5 CU_0)
(* 0.5 CU_N))))
(do ((x 0 (1+ x))) ((>= x 8))
(f64vector-set! F μ
(+ (f64vector-ref F μ)
(* coef
(f64vector-ref f x)
(cos (/ (* μ π (+ 1.0 (* 2.0 x)))
16.0))))))))
F))
(define (dct-f64-inverse-8-point F)
(let ((f (make-f64vector 8 0.0)))
(do ((x 0 (1+ x))) ((>= x 8))
(do ((μ 0 (1+ μ))) ((>= μ 8))
(let ((coef (if (zero? μ)
(* 0.5 CU_0)
(* 0.5 CU_N))))
(f64vector-set! f x
(+ (f64vector-ref f x)
(* coef
(f64vector-ref F μ)
(cos (/ (* μ π (+ 1.0 (* 2.0 x)))
16.0))))))))
f))
(define (deal n low high)
"Return a list of N distinct integers with values between
LOW (inclusive) and HIGH (exclusive)."
(let loop ((i 0)
(lst (map (lambda (x) (+ x low)) (iota (- high low))))
(out '()))
(if (>= i n)
out
(let ((j (random (length lst))))
(loop (1+ i)
(append (take lst j) (drop lst (1+ j)))
(append out (list (list-ref lst j))))))))
(define (gauss-legendre-quadrature proc n)
"Integrate PROC, a procedure that maps a number to a number,
over the range -1 to 1, using a Nth order approximation, where
2 <= N <= 6"
(let ((nodes/weights '(;; n = 2
((-0.5773502692 . 1.0000000000)
( 0.5773502692 . 1.0000000000))
;; n = 3
((-0.7745966692 . 0.5555555556)
( 0.0000000000 . 0.8888888889)
( 0.7745966692 . 0.5555555556))
;; n = 4
((-0.8611363316 . 0.3478588451)
( 0.3399810436 . 0.6521451549)
( 0.8611363316 . 0.3478588451))
;; n = 5
((-0.9061797459 . 0.2369268851)
(-0.5384693101 . 0.4786286705)
( 0.0000000000 . 0.5688888889)
( 0.5384693101 . 0.4786286705)
( 0.9061797459 . 0.2369268851))
;; n = 6
((-0.9324695142 . 0.1713244924)
(-0.6612093865 . 0.3607615730)
(-0.2386191861 . 0.4679139346)
( 0.2386191861 . 0.4679139346)
( 0.6612093865 . 0.3607615730)
( 0.9324695142 . 0.1713244924)))))
(let ((nw (list-ref nodes/weights (- n 2))))
(let loop ((i 0)
(sum 0.0))
(if (< i n)
(let ((nw-cur (list-ref nw i)))
(format #t "nw-cur ~s nw ~s i ~s ~%" nw-cur nw i)
(loop (1+ i)
(+ sum (* (cdr nw-cur)
(proc (car nw-cur))))))
;; else
sum)))))
(define (legendre-polynomial n x)
"Computes the nth order Legendre polynomial at the location
x, where x is [-1, 1]."
;; Using the explicit expression
;; P_n(x) = (1 / 2^n) * SUM_0^floor(n/2) -1^m (binom n m) (binom 2n-2m n) x&(n-2m
;;
(cond
((= n 0)
1)
((= n 1)
x)
((= n 2)
(* 1/2 (+ (* 3 x x) -1)))
((= n 3)
(* 1/2 (+ (* 5 x x x) (* -3 x))))
((= n 4)
(* 1/8 (+ (* 35 (expt x 4)) (* -30 x x) 3)))
(else
(let ((A (/ 1 (expt 2 n)))
(range (floor (/ n 2))))
(* A
(let loop ((m 0)
(sum 0))
(if (<= m range)
(let ((sgn (expt -1 m))
(B (binomial-coefficient n m))
(C (binomial-coefficient (- (* 2 n) (* 2 m)) n))
(D (expt 1 (- n (* 2 m)))))
(loop (1+ m)
(+ sum (* sgn B C D))))
;; else
sum)))))))
(define (lognot-uint8 x)
"Find the bitwise complement of an 8-bit unsigned integer."
(lognot-uint x 1))
(define (lognot-uint16 x)
"Find the bitwise complement of a 16-bit unsigned integer."
(lognot-uint x 2))
(define (lognot-uint32 x)
"Find the bitwise complement of a 32-bit unsigned integer."
(lognot-uint x 4))
(define (lognot-uint64 x)
"Find the bitwise complement of a 64-bit unsigned integer."
(lognot-uint x 8))
(define (f32-2d-make-array m n)
"Make a standard 2D array m (rows) by n (columns) matrix for floating
point math. It is initialized to zero."
(make-typed-array 'f32 0.0 `(1 ,m) `(1 ,n)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; F32D2 Arrays and Vectors
;;
;; The following procedure are for two-dimensional float32 arrays and
;; vectors that follow standard linear and matrix algebra conventions.
;; Vectors are arrays with width=1 column vectors or height=1 row vectors.
;; Array sizes are listed as m by n, aka row by cols, aka height by width.
;; Array indices are (i,j), aka (y,x), aka (row,col)
;; Array limits are 1 <= i <= m. 1 <= j <= n.
(define (f32d2-make-column-vector m)
"Make a standard 1D column vector with m rows for floating point math,
initialized to zero."
(f32d2-make-array m 1))
(define (f32d2-make-row-vector n)
"Make a standard 1D row vector with n columns for floating point math,
initialized to zero."
(f32d2-make-array 1 n))
(define (f32d2-height arr)
"The height (aka y_max, aka m) of the given array"
)
(define (f32d2-width arr)
"The width (aka x_max, aka n) of the given array"
)
(define (f32d2-length arr)
"The longer of the height or width of the given array.
For a both a row vector and a column vector, it returns the number of
elements." )
(define (f32d2-size arr)
"Returns the height by width, (aka m by n, aka y_max by x_max)
for the given array."
)
(define (f32d2-zeros m n)
"Create an m by n array of all zeros."
)
(define (f32d2-ones m n)
"Create a m by n array of all ones."
)
(define (f32d2-rand m n)
"Create a m by n array of random numbers between zero and one."
)
(define (f32d2-identity m n)
"Create an m by n matrix that is one on the main diagonal
and zero elsewhere"
)
(define (f32d2-vector-to-diagonal vec)
"Given a row or column vector of length n,
returns a diagonal n by n matrix with the elements of
the vector as the diagonal."
)
(define (f32d2-horizontal-concatenate arr1 arr2)
"Given two arrays with the same number of rows, return
a new array which is the horizontal concatenation of
the arrays."
)
(define (f32d2-vertical-concatenate arr1 arr2)
"Given two arrays with the same number of columns, return
a new array which is the horizontal concatenation of
the arrays."
)
;; f32d2-linspace - linearly spaced vector
;; f32d20logspace - log spaced vector
;; f32-meshgrid - linearly spaced 2d-grid
;; is-row-vector? is-col-vector? is-matrix? is-empty?
;; sort
;; flip
;; rot90
;; transpose
;;
(define (f32d2-array-row-count arr)
(second (first (array-shape arr))))
(define (f32d2-array-col-count arr)
(second (second (array-shape arr))))
(define (f32d2-array-dimensions arr)
(list (f32d2-array-row-count arr)
(f32d2-array-col-count arr)))
(define (f32d2-array-sum arr1 arr2)
"Sum the elements of two f32d2-arrays. The arrays must have
the same dimensions."
(let ((dim1 (f32d2-array-dimensions arr1))
(dim2 (f32d2-array-dimensions arr2)))
(let ((arr3 (apply f32d2-make-array dim1)))
(do ((j 1 (1+ j))) ((> j (second dim1)))
(do ((i 1 (1+ i))) ((> i (first dim1)))
(array-set! arr3
(+ (array-ref arr1 i j)
(array-ref arr2 i j))
i j)))
arr3)))
(define (f32d2-transpose-array arr)
(let* ((orig-row (f32d2-array-row-count arr))
(orig-col (f32d2-array-col-count arr)))
(let ((arr2 (f32d2-make-array orig-col orig-row)))
(do ((i 1 (1+ i))) ((> i orig-row))
(do ((j 1 (1+ j))) ((> j orig-col))
(array-set! arr2
(array-ref arr i j)
j i)))
arr2)))
(define (monotonic-list-pos-to-coord lst x)
"Given a list of monotonically increasing integers (x1 x2 x3 ...)
this returns a pair.
The first element is
0 if 0 <= x < x1
1 if x1 <= x < x2
2 if x2 <= x < x3, etc.
The second element is the difference between x and the lower limit.
Thus ((list 5 10 15) 7) => (1 2)
since x1 <= 7 and 7 - x1 = 2"
(let loop ((j 0)
(prev 0)
(cur (car lst))
(rest (cdr lst)))
(if (and (<= prev x) (< x cur))
(list j (- x prev))
(loop (1+ j) cur (car rest) (cdr rest)))))
(define (pythag x y)
(sqrt (+ (* x x) (* y y))))
(define (sign x)
(if (< x 0)
-1
1))
(define (rotg sa sb)
"Construct Givens plane rotation.
Given a vector (sa, sb). Compute the length, the ???, and the
direction sine and cosine."
(let ((asa (abs sa))
(asb (abs sb)))
(let ((sgn (if (< asa asb)
(sign sa)
(sign sb)))
(scale (+ asa asb)))
(if (zero? scale)
;; (R Z C S)
'(0.0 0.0 1.0 0.0)
;; else
(let* ((r (* sgn scale (pythag (/ sa scale) (/ sb scale))))
(c (/ sa r))
(s (/ sb r))
(z (if (> asa asb)
s
;; else
(if (zero? c)
1.0
(/ 1.0 c)))))
(list r z c s))))))
(define (quadratic-roots a b c)
"Given a quadratic equation Ax^2 + Bx + C = 0, find the roots."
(if (zero? a)
(if (zero? b)
'()
;; else
(list (/ (- c) b)))
;; else
(let* ((det (if (>= b 0)
(sqrt (- (* b b) (* 4 a c)))
(- (sqrt (- (* b b) (* 4 a c))))))
(q (* -0.5 (+ b det))))
(list (/ q a) (/ c q)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 8.3.2 Numerical Differentiation
;; CRC Math 30th Ed, p 705
(define (derivative-estimate-forward-two-point-formula func x0 h)
"Finds an estimate of the derivative of func at x0, using
h as a step size."
(* (/ 1 h)
(- (func (- x0 h))
(func x0))))
(define deriv2F derivative-estimate-forward-two-point-formula)
(define (derivative-estimate-forward-three-point-formula func x0 h)
(* (/ 1 (* 2 h))
(+ (* -3 (func x0))
(* 4 (func (+ x0 h)))
(func (+ x0 h h)))))
(define deriv3F derivative-estimate-forward-three-point-formula)
(define (derivative-estimate-two-point-formula func x0 h)
(* (/ 1 (* 2 h))
(- (func (+ x0 h)) (func (- x0 h)))))
(define deriv2 derivative-estimate-two-point-formula)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; For C-defined functions
(define *math-lib-loaded* #f)
(define (math-load-extension)
(unless *math-lib-loaded*
(set! *math-lib-loaded* #t)
(load-extension "libmlg" "init_math_lib")))
| false |
03e5b2485e1cbc573b0095b32d3e5d2d7dbf87d2
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System/system/net/download-progress-changed-event-args.sls
|
269940c21945e3d050311b9e62e40163bf521aa1
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 726 |
sls
|
download-progress-changed-event-args.sls
|
(library (system net download-progress-changed-event-args)
(export is?
download-progress-changed-event-args?
bytes-received
total-bytes-to-receive)
(import (ironscheme-clr-port))
(define (is? a)
(clr-is System.Net.DownloadProgressChangedEventArgs a))
(define (download-progress-changed-event-args? a)
(clr-is System.Net.DownloadProgressChangedEventArgs a))
(define-field-port
bytes-received
#f
#f
(property:)
System.Net.DownloadProgressChangedEventArgs
BytesReceived
System.Int64)
(define-field-port
total-bytes-to-receive
#f
#f
(property:)
System.Net.DownloadProgressChangedEventArgs
TotalBytesToReceive
System.Int64))
| false |
b1cbe6dbd572c51c931e28c778656ef69bb4e4de
|
ae0d7be8827e8983c926f48a5304c897dc32bbdc
|
/Gauche-tir/trunk/lib/tir04/cgi/session.scm
|
41775e46e9ff5ee7573f7becf864891008a0d55a
|
[
"MIT"
] |
permissive
|
ayamada/copy-of-svn.tir.jp
|
96c2176a0295f60928d4911ce3daee0439d0e0f4
|
101cd00d595ee7bb96348df54f49707295e9e263
|
refs/heads/master
| 2020-04-04T01:03:07.637225 | 2015-05-28T07:00:18 | 2015-05-28T07:00:18 | 1,085,533 | 3 | 2 | null | 2015-05-28T07:00:18 | 2010-11-16T15:56:30 |
Scheme
|
EUC-JP
|
Scheme
| false | false | 4,608 |
scm
|
session.scm
|
;;; coding: euc-jp
;;; -*- scheme -*-
;;; vim:set ft=scheme ts=8 sts=2 sw=2 et:
;;; $Id$
;;; 概要:
;;; CGI用セッションマネージャ。
;;; セッションはcookieに保存される。
;;; note: セッションに#fを保存する事はできない。
;;; (cgi-with-session時に、セッションが無いのか、#fが入っているのか
;;; 判断できなくなる為。)
;;; #fを保存しようとすると、既存のセッションを削除する仕様とした。
;;; #f相当を保存したい時は、'(#f)等にすべき。
;;; note: このモジュールでは、expiresを設定したクッキーは使用できない。
;;; (用途がセッションの為。)
#|
(define *cgi-session*
(make
<cgi-session>
:dbm-type <fsdbm>
:dbm-path "/path/to/dbm-file"
:expire-second (* 1 24 60 60)
:cookie-name "cgi-session"
:cookie-keywords '(:discard #t :path "/") ; expiresは設定しない事
))
(cgi-main
(lambda (params)
(cgi-with-session
*cgi-session*
(lambda (session-data)
...
))))
|#
(define-module tir04.cgi.session
(use gauche.parameter)
(use rfc.cookie)
(use www.cgi)
(extend tir04.session.dbm)
(export
<cgi-session>
cgi-with-session
cgi-create-session!
cgi-update-session!
cgi-remove-session!
))
(select-module tir04.cgi.session)
(define-class <cgi-session> (<session-dbm>)
(
;; セッションクッキーについての情報
(cookie-name
:accessor cookie-name-of
:init-keyword :cookie-name
:init-value "cgi-session")
;; keywordsの詳細は、rfc.cookieのconstruct-cookie-stringを参照
(cookie-keywords
:accessor cookie-keywords-of
:init-keyword :cookie-keywords
:init-value '(
:discard #t
:path "/"
))
;; 整形されたSet-Cookieヘッダを一時的に記憶するスロット
(cookie-headers
:accessor cookie-headers-of
:init-form (make-parameter #f))
;; その他のスロットについては、<session-dbm>と<session>を参照
))
(define-method initialize ((self <cgi-session>) initargs)
(next-method)
;; 今のところは、特に処理無し
#t)
;;; --------
(define-method cgi-with-session ((self <cgi-session>) proc)
;; note: 以下の点が、元のwith-sessionと異なっている。
;; - cookieからsidを読み出す事。
;; - procの返り値に、必要であればSet-Cookieヘッダを追加する事。
;; note: もし今後、クッキーにexpiresを使えるようにする場合は、
;; この手続きは毎回、Set-Cookieを出力するように直す必要がある。
(let1 sid (cgi-get-parameter
(cookie-name-of self)
(cgi-parse-parameters :query-string ""
:merge-cookies #t))
(parameterize (((cookie-headers-of self) '()))
(let1 result (with-session self sid proc)
(list ((cookie-headers-of self)) result)))))
(define-method cgi-create-session! ((self <cgi-session>) session-data)
(let1 sid (create-session! self session-data)
;; ((cookie-headers-of self))を更新する
((cookie-headers-of self) (list
"Set-Cookie: "
(car ; 今のところ、cookieは一つ固定
(construct-cookie-string
`((,(cookie-name-of self) ,sid
,@(cookie-keywords-of self)))
0))
"\r\n"))))
(define-method cgi-create-session! (session-data)
(unless (cgi-session)
(error "cannot found <cgi-session>"))
(cgi-create-session! (cgi-session) session-data))
(define-method cgi-update-session! ((self <cgi-session>) session-data)
;; 今のところ、追加が必要な処理は無し
(update-session! self session-data))
(define-method cgi-update-session! (session-data)
(unless (cgi-session)
(error "cannot found <cgi-session>"))
(cgi-update-session! (cgi-session) session-data))
(define-method cgi-remove-session! ((self <cgi-session>))
;; 今のところ、追加が必要な処理は無し
;; (可能なら、古いクッキーも消すようにしたいが、ちょっと無理っぽい)
(remove-session! self))
(define-method cgi-remove-session! ()
(unless (cgi-session)
(error "cannot found <cgi-session>"))
(cgi-remove-session! (cgi-session)))
;;; --------
(provide "tir04/cgi/session")
| false |
7073433040f12aedb6bfd540063eea3d42083c12
|
951b7005abfe3026bf5b3bd755501443bddaae61
|
/compose.scm
|
d680e0aebe69d2db3c5aa1a1549c355b2bd003e8
|
[] |
no_license
|
WingT/scheme-sicp
|
d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61
|
a255f3e43b46f89976d8ca2ed871057cbcbb8eb9
|
refs/heads/master
| 2020-05-21T20:12:17.221412 | 2016-09-24T14:56:49 | 2016-09-24T14:56:49 | 63,522,759 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 531 |
scm
|
compose.scm
|
(define (compose f g)
(lambda (x) (f (g x))))
(define (squar x) (* x x))
(define (inc x) (+ x 1))
(define (repeated f n)
(define (repeated-iter k g)
(if (= k n)
g
(repeated-iter (+ k 1) (lambda (x) (f (g x))))))
(repeated-iter 1 f))
((repeated square 2) 5)
(define (smooth f)
(define dx 0.00005)
(lambda (x) (/ (+ (f x) (f (- x dx)) (f (+ x dx))) 3.0)))
(define (smooth-n f n)
(define (smooth-n-iter k g)
(if (= k n)
g
(smooth-n-iter (+ 1 k) (smooth g))))
(smooth-n-iter 0 f))
| false |
c5c5a6aa5fbf467ec80571192ea4a2efd2ea08b7
|
2fc7c18108fb060ad1f8d31f710bcfdd3abc27dc
|
/contrib/prolog-test.scm
|
b59ab0fd85ac6d736e9423d26380f1fe0d134c9f
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0"
] |
permissive
|
bakul/s9fes
|
97a529363f9a1614a85937a5ef9ed6685556507d
|
1d258c18dedaeb06ce33be24366932143002c89f
|
refs/heads/master
| 2023-01-24T09:40:47.434051 | 2022-10-08T02:11:12 | 2022-10-08T02:11:12 | 154,886,651 | 68 | 10 |
NOASSERTION
| 2023-01-25T17:32:54 | 2018-10-26T19:49:40 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,095 |
scm
|
prolog-test.scm
|
; Sample PROLOG program
; By Nils M Holm, 1998-2009
; Placed in the Public Domain
;
; To load this program, run
;
; (load-from-library "prolog-test.scm")
;
; Then try some queries like
;
; (? (female ?who)) ; Which females are there?
; (? (_ eric ?who)) ; Which relatives does Eric have?
; (? (?relation cathy ?who)) ; Cathy is related to whom in which way?
(load-from-library "prolog.scm")
(new-database!) ; set up fresh database
(! (female cathy)) ; add some facts
(! (female denise))
(! (female fanny))
(! (male anthony))
(! (male bertram))
(! (male eric))
(! (parent bertram eric))
(! (parent cathy eric))
(! (parent anthony cathy))
(! (parent eric denise))
(! (parent anthony fanny))
(! (wife cathy bertram))
(:- (husband ?a ?b) (wife ?b ?a)) ; define some predicates
(:- (mother ?a ?b) (female ?a)
(parent ?a ?b))
(:- (father ?a ?b) (male ?a)
(parent ?a ?b))
(:- (child ?a ?b) (parent ?b ?a))
(:- (descendant ?a ?b) (child ?a ?b))
(:- (descendant ?a ?b) (child ?a ?x)
(descendant ?x ?b))
| false |
d0ae9a34c07026d04acdb9ff0271b4084e0d8ebd
|
c27f74958de01e46f2ead89e1ab6c952dc8238ad
|
/usr/share/guile/2.2/language/tree-il/compile-cps.scm
|
62bf7933e5989da7bc62f0f83a12fd0c4aa50ea8
|
[] |
no_license
|
git-for-windows/git-sdk-32
|
051ab8b76e3eb68126fc31dcc061f0d93341bb8d
|
e948a750b18992de20c64155e8c6959c475748ed
|
refs/heads/main
| 2023-08-31T21:32:13.595310 | 2023-08-30T11:37:43 | 2023-08-30T11:37:43 | 87,077,227 | 36 | 64 | null | 2023-08-25T08:34:40 | 2017-04-03T13:29:09 |
C
|
UTF-8
|
Scheme
| false | false | 47,042 |
scm
|
compile-cps.scm
|
;;; Continuation-passing style (CPS) intermediate language (IL)
;; Copyright (C) 2013, 2014, 2015, 2017, 2018 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;;;
;;; This pass converts Tree-IL to the continuation-passing style (CPS)
;;; language.
;;;
;;; CPS is a lower-level representation than Tree-IL. Converting to
;;; CPS, beyond adding names for all control points and all values,
;;; simplifies expressions in the following ways, among others:
;;;
;;; * Fixing the order of evaluation.
;;;
;;; * Converting assigned variables to boxed variables.
;;;
;;; * Requiring that Scheme's <letrec> has already been lowered to
;;; <fix>.
;;;
;;; * Inlining default-value initializers into lambda-case
;;; expressions.
;;;
;;; * Inlining prompt bodies.
;;;
;;; * Turning toplevel and module references into primcalls. This
;;; involves explicitly modelling the "scope" of toplevel lookups
;;; (indicating the module with respect to which toplevel bindings
;;; are resolved).
;;;
;;; The utility of CPS is that it gives a name to everything: every
;;; intermediate value, and every control point (continuation). As such
;;; it is more verbose than Tree-IL, but at the same time more simple as
;;; the number of concepts is reduced.
;;;
;;; Code:
(define-module (language tree-il compile-cps)
#:use-module (ice-9 match)
#:use-module ((srfi srfi-1) #:select (fold filter-map))
#:use-module (srfi srfi-26)
#:use-module ((system foreign) #:select (make-pointer pointer->scm))
#:use-module (language cps)
#:use-module (language cps utils)
#:use-module (language cps with-cps)
#:use-module (language cps primitives)
#:use-module (language tree-il analyze)
#:use-module (language tree-il optimize)
#:use-module (language tree-il)
#:use-module (language cps intmap)
#:export (compile-cps))
;;; Guile's semantics are that a toplevel lambda captures a reference on
;;; the current module, and that all contained lambdas use that module
;;; to resolve toplevel variables. This parameter tracks whether or not
;;; we are in a toplevel lambda. If we are in a lambda, the parameter
;;; is bound to a fresh name identifying the module that was current
;;; when the toplevel lambda is defined.
;;;
;;; This is more complicated than it need be. Ideally we should resolve
;;; all toplevel bindings to bindings from specific modules, unless the
;;; binding is unbound. This is always valid if the compilation unit
;;; sets the module explicitly, as when compiling a module, but it
;;; doesn't work for files auto-compiled for use with `load'.
;;;
(define current-topbox-scope (make-parameter #f))
(define scope-counter (make-parameter #f))
(define (fresh-scope-id)
(let ((scope-id (scope-counter)))
(scope-counter (1+ scope-id))
scope-id))
(define (toplevel-box cps src name bound? val-proc)
(define (lookup cps name bound? k)
(match (current-topbox-scope)
(#f
(with-cps cps
(build-term ($continue k src
($primcall 'resolve (name bound?))))))
(scope-id
(with-cps cps
($ (with-cps-constants ((scope scope-id))
(build-term
($continue k src
($primcall 'cached-toplevel-box (scope name bound?))))))))))
(with-cps cps
(letv box)
(let$ body (val-proc box))
(letk kbox ($kargs ('box) (box) ,body))
($ (with-cps-constants ((name name)
(bound? bound?))
($ (lookup name bound? kbox))))))
(define (module-box cps src module name public? bound? val-proc)
(with-cps cps
(letv box)
(let$ body (val-proc box))
(letk kbox ($kargs ('box) (box) ,body))
($ (with-cps-constants ((module module)
(name name)
(public? public?)
(bound? bound?))
(build-term ($continue kbox src
($primcall 'cached-module-box
(module name public? bound?))))))))
(define (capture-toplevel-scope cps src scope-id k)
(with-cps cps
(letv module)
(let$ body (with-cps-constants ((scope scope-id))
(build-term
($continue k src
($primcall 'cache-current-module! (module scope))))))
(letk kmodule ($kargs ('module) (module) ,body))
(build-term ($continue kmodule src
($primcall 'current-module ())))))
(define (fold-formals proc seed arity gensyms inits)
(match arity
(($ $arity req opt rest kw allow-other-keys?)
(let ()
(define (fold-req names gensyms seed)
(match names
(() (fold-opt opt gensyms inits seed))
((name . names)
(proc name (car gensyms) #f
(fold-req names (cdr gensyms) seed)))))
(define (fold-opt names gensyms inits seed)
(match names
(() (fold-rest rest gensyms inits seed))
((name . names)
(proc name (car gensyms) (car inits)
(fold-opt names (cdr gensyms) (cdr inits) seed)))))
(define (fold-rest rest gensyms inits seed)
(match rest
(#f (fold-kw kw gensyms inits seed))
(name (proc name (car gensyms) #f
(fold-kw kw (cdr gensyms) inits seed)))))
(define (fold-kw kw gensyms inits seed)
(match kw
(()
(unless (null? gensyms)
(error "too many gensyms"))
(unless (null? inits)
(error "too many inits"))
seed)
(((key name var) . kw)
;; Could be that var is not a gensym any more.
(when (symbol? var)
(unless (eq? var (car gensyms))
(error "unexpected keyword arg order")))
(proc name (car gensyms) (car inits)
(fold-kw kw (cdr gensyms) (cdr inits) seed)))))
(fold-req req gensyms seed)))))
(define (unbound? cps src var kt kf)
(define tc8-iflag 4)
(define unbound-val 9)
(define unbound-bits (logior (ash unbound-val 8) tc8-iflag))
(with-cps cps
($ (with-cps-constants ((unbound (pointer->scm
(make-pointer unbound-bits))))
(build-term ($continue kf src
($branch kt ($primcall 'eq? (var unbound)))))))))
(define (init-default-value cps name sym subst init body)
(match (hashq-ref subst sym)
((orig-var subst-var box?)
(let ((src (tree-il-src init)))
(define (maybe-box cps k make-body)
(if box?
(with-cps cps
(letv phi)
(letk kbox ($kargs (name) (phi)
($continue k src ($primcall 'box (phi)))))
($ (make-body kbox)))
(make-body cps k)))
(with-cps cps
(letk knext ($kargs (name) (subst-var) ,body))
($ (maybe-box
knext
(lambda (cps k)
(with-cps cps
(letk kbound ($kargs () () ($continue k src
($values (orig-var)))))
(letv val rest)
(letk krest ($kargs (name 'rest) (val rest)
($continue k src ($values (val)))))
(letk kreceive ($kreceive (list name) 'rest krest))
(let$ init (convert init kreceive subst))
(letk kunbound ($kargs () () ,init))
($ (unbound? src orig-var kunbound kbound)))))))))))
;;; The conversion from Tree-IL to CPS essentially wraps every
;;; expression in a $kreceive, which models the Tree-IL semantics that
;;; extra values are simply truncated. In CPS, this means that the
;;; $kreceive has a rest argument after the required arguments, if any,
;;; and that the rest argument is unused.
;;;
;;; All CPS expressions that can return a variable number of values
;;; (i.e., $call and $abort) must continue to $kreceive, which checks
;;; the return arity and on success passes the parsed values along to a
;;; $kargs. If the $call or $abort is in tail position they continue to
;;; $ktail instead, and then the values are parsed by the $kreceive of
;;; the non-tail caller.
;;;
;;; Other CPS terms like $values, $const, and the like all have a
;;; specific return arity, and must continue to $kargs instead of
;;; $kreceive or $ktail. This allows the compiler to reason precisely
;;; about their result values. To make sure that this is the case,
;;; whenever the CPS conversion would reify one of these terms it needs
;;; to ensure that the continuation actually accepts the return arity of
;;; the primcall.
;;;
;;; Some Tree-IL primcalls residualize CPS primcalls that return zero
;;; values, for example box-set!. In this case the Tree-IL semantics
;;; are that the result of the expression is the undefined value. That
;;; is to say, the result of this expression is #t:
;;;
;;; (let ((x 30)) (eq? (set! x 10) (if #f #f)))
;;;
;;; So in the case that the continuation expects a value but the
;;; primcall produces zero values, we insert the "unspecified" value.
;;;
(define (adapt-arity cps k src nvals)
(match nvals
(0
;; As mentioned above, in the Tree-IL semantics the primcall
;; produces the unspecified value, but in CPS it produces no
;; values. Therefore we plug the unspecified value into the
;; continuation.
(match (intmap-ref cps k)
(($ $ktail)
(with-cps cps
(let$ body (with-cps-constants ((unspecified *unspecified*))
(build-term
($continue k src ($values (unspecified))))))
(letk kvoid ($kargs () () ,body))
kvoid))
(($ $kargs ()) (with-cps cps k))
(($ $kreceive arity kargs)
(match arity
(($ $arity () () (not #f) () #f)
(with-cps cps
(letk kvoid ($kargs () () ($continue kargs src ($const '()))))
kvoid))
(($ $arity (_) () #f () #f)
(with-cps cps
(letk kvoid ($kargs () ()
($continue kargs src ($const *unspecified*))))
kvoid))
(($ $arity (_) () _ () #f)
(with-cps cps
(let$ void (with-cps-constants ((unspecified *unspecified*)
(rest '()))
(build-term
($continue kargs src
($values (unspecified rest))))))
(letk kvoid ($kargs () () ,void))
kvoid))
(_
;; Arity mismatch. Serialize a values call.
(with-cps cps
(let$ void (with-cps-constants ((unspecified *unspecified*))
(build-term
($continue k src
($primcall 'values (unspecified))))))
(letk kvoid ($kargs () () ,void))
kvoid))))))
(1
(match (intmap-ref cps k)
(($ $ktail)
(with-cps cps
(letv val)
(letk kval ($kargs ('val) (val)
($continue k src ($values (val)))))
kval))
(($ $kargs (_)) (with-cps cps k))
(($ $kreceive arity kargs)
(match arity
(($ $arity () () (not #f) () #f)
(with-cps cps
(letv val)
(let$ body (with-cps-constants ((nil '()))
(build-term
($continue kargs src ($primcall 'cons (val nil))))))
(letk kval ($kargs ('val) (val) ,body))
kval))
(($ $arity (_) () #f () #f)
(with-cps cps
kargs))
(($ $arity (_) () _ () #f)
(with-cps cps
(letv val)
(let$ body (with-cps-constants ((rest '()))
(build-term
($continue kargs src ($values (val rest))))))
(letk kval ($kargs ('val) (val) ,body))
kval))
(_
;; Arity mismatch. Serialize a values call.
(with-cps cps
(letv val)
(letk kval ($kargs ('val) (val)
($continue k src
($primcall 'values (val)))))
kval))))))))
;; cps exp k-name alist -> cps term
(define (convert cps exp k subst)
(define (zero-valued? exp)
(match exp
((or ($ <module-set>) ($ <toplevel-set>) ($ <toplevel-define>)
($ <lexical-set>))
#t)
(($ <let> src names syms vals body) (zero-valued? body))
;; Can't use <fix> here as the hack that <fix> uses to convert its
;; functions relies on continuation being single-valued.
;; (($ <fix> src names syms vals body) (zero-valued? body))
(($ <let-values> src exp body) (zero-valued? body))
(($ <seq> src head tail) (zero-valued? tail))
(($ <primcall> src name args)
(match (prim-instruction name)
(#f #f)
(inst
(match (prim-arity inst)
((out . in)
(and (eqv? out 0)
(eqv? in (length args))))))))
(_ #f)))
(define (single-valued? exp)
(match exp
((or ($ <void>) ($ <const>) ($ <primitive-ref>) ($ <module-ref>)
($ <toplevel-ref>) ($ <lambda>))
#t)
(($ <let> src names syms vals body) (single-valued? body))
(($ <fix> src names syms vals body) (single-valued? body))
(($ <let-values> src exp body) (single-valued? body))
(($ <seq> src head tail) (single-valued? tail))
(($ <primcall> src name args)
(match (prim-instruction name)
(#f #f)
(inst
(match (prim-arity inst)
((out . in)
(and (eqv? out 1)
(eqv? in (length args))))))))
(_ #f)))
;; exp (v-name -> term) -> term
(define (convert-arg cps exp k)
(match exp
(($ <lexical-ref> src name sym)
(match (hashq-ref subst sym)
((orig-var box #t)
(with-cps cps
(letv unboxed)
(let$ body (k unboxed))
(letk kunboxed ($kargs ('unboxed) (unboxed) ,body))
(build-term ($continue kunboxed src ($primcall 'box-ref (box))))))
((orig-var subst-var #f) (k cps subst-var))
(var (k cps var))))
((? single-valued?)
(with-cps cps
(letv arg)
(let$ body (k arg))
(letk karg ($kargs ('arg) (arg) ,body))
($ (convert exp karg subst))))
(_
(with-cps cps
(letv arg rest)
(let$ body (k arg))
(letk karg ($kargs ('arg 'rest) (arg rest) ,body))
(letk kreceive ($kreceive '(arg) 'rest karg))
($ (convert exp kreceive subst))))))
;; (exp ...) ((v-name ...) -> term) -> term
(define (convert-args cps exps k)
(match exps
(() (k cps '()))
((exp . exps)
(convert-arg cps exp
(lambda (cps name)
(convert-args cps exps
(lambda (cps names)
(k cps (cons name names)))))))))
(define (box-bound-var cps name sym body)
(match (hashq-ref subst sym)
((orig-var subst-var #t)
(with-cps cps
(letk k ($kargs (name) (subst-var) ,body))
(build-term ($continue k #f ($primcall 'box (orig-var))))))
(else
(with-cps cps body))))
(define (box-bound-vars cps names syms body)
(match (vector names syms)
(#((name . names) (sym . syms))
(with-cps cps
(let$ body (box-bound-var name sym body))
($ (box-bound-vars names syms body))))
(#(() ()) (with-cps cps body))))
(define (bound-var sym)
(match (hashq-ref subst sym)
((var . _) var)
((? exact-integer? var) var)))
(match exp
(($ <lexical-ref> src name sym)
(with-cps cps
(let$ k (adapt-arity k src 1))
(rewrite-term (hashq-ref subst sym)
((orig-var box #t) ($continue k src ($primcall 'box-ref (box))))
((orig-var subst-var #f) ($continue k src ($values (subst-var))))
(var ($continue k src ($values (var)))))))
(($ <void> src)
(with-cps cps
(let$ k (adapt-arity k src 1))
(build-term ($continue k src ($const *unspecified*)))))
(($ <const> src exp)
(with-cps cps
(let$ k (adapt-arity k src 1))
(build-term ($continue k src ($const exp)))))
(($ <primitive-ref> src name)
(with-cps cps
(let$ k (adapt-arity k src 1))
(build-term ($continue k src ($prim name)))))
(($ <lambda> fun-src meta body)
(let ()
(define (convert-clauses cps body ktail)
(match body
(#f (values cps #f))
(($ <lambda-case> src req opt rest kw inits gensyms body alternate)
(let* ((arity (make-$arity req (or opt '()) rest
(map (match-lambda
((kw name sym)
(list kw name (bound-var sym))))
(if kw (cdr kw) '()))
(and kw (car kw))))
(names (fold-formals (lambda (name sym init names)
(cons name names))
'()
arity gensyms inits)))
(define (fold-formals* cps f seed arity gensyms inits)
(match (fold-formals
(lambda (name sym init cps+seed)
(match cps+seed
((cps . seed)
(call-with-values (lambda ()
(f cps name sym init seed))
(lambda (cps seed) (cons cps seed))))))
(cons cps seed) arity gensyms inits)
((cps . seed) (values cps seed))))
(with-cps cps
(let$ kalt (convert-clauses alternate ktail))
(let$ body (convert body ktail subst))
(let$ body
(fold-formals*
(lambda (cps name sym init body)
(if init
(init-default-value cps name sym subst init body)
(box-bound-var cps name sym body)))
body arity gensyms inits))
(letk kargs ($kargs names (map bound-var gensyms) ,body))
(letk kclause ($kclause ,arity kargs kalt))
kclause)))))
(if (current-topbox-scope)
(with-cps cps
(letv self)
(letk ktail ($ktail))
(let$ kclause (convert-clauses body ktail))
(letk kfun ($kfun fun-src meta self ktail kclause))
(let$ k (adapt-arity k fun-src 1))
(build-term ($continue k fun-src ($fun kfun))))
(let ((scope-id (fresh-scope-id)))
(with-cps cps
(let$ body ((lambda (cps)
(parameterize ((current-topbox-scope scope-id))
(convert cps exp k subst)))))
(letk kscope ($kargs () () ,body))
($ (capture-toplevel-scope fun-src scope-id kscope)))))))
(($ <module-ref> src mod name public?)
(module-box
cps src mod name public? #t
(lambda (cps box)
(with-cps cps
(let$ k (adapt-arity k src 1))
(build-term ($continue k src ($primcall 'box-ref (box))))))))
(($ <module-set> src mod name public? exp)
(convert-arg cps exp
(lambda (cps val)
(module-box
cps src mod name public? #t
(lambda (cps box)
(with-cps cps
(let$ k (adapt-arity k src 0))
(build-term
($continue k src ($primcall 'box-set! (box val))))))))))
(($ <toplevel-ref> src name)
(toplevel-box
cps src name #t
(lambda (cps box)
(with-cps cps
(let$ k (adapt-arity k src 1))
(build-term ($continue k src ($primcall 'box-ref (box))))))))
(($ <toplevel-set> src name exp)
(convert-arg cps exp
(lambda (cps val)
(toplevel-box
cps src name #f
(lambda (cps box)
(with-cps cps
(let$ k (adapt-arity k src 0))
(build-term
($continue k src ($primcall 'box-set! (box val))))))))))
(($ <toplevel-define> src name exp)
(convert-arg cps exp
(lambda (cps val)
(with-cps cps
(let$ k (adapt-arity k src 0))
(letv box)
(letk kset ($kargs ('box) (box)
($continue k src ($primcall 'box-set! (box val)))))
($ (with-cps-constants ((name name))
(build-term
($continue kset src ($primcall 'define! (name))))))))))
(($ <call> src proc args)
(convert-args cps (cons proc args)
(match-lambda*
((cps (proc . args))
(with-cps cps
(build-term ($continue k src ($call proc args))))))))
(($ <primcall> src name args)
(cond
((eq? name 'equal?)
(convert-args cps args
(lambda (cps args)
(with-cps cps
(let$ k* (adapt-arity k src 1))
(letk kt ($kargs () () ($continue k* src ($const #t))))
(letk kf* ($kargs () ()
;; Here we continue to the original $kreceive
;; or $ktail, as equal? doesn't have a VM op.
($continue k src ($primcall 'equal? args))))
(build-term ($continue kf* src
($branch kt ($primcall 'eqv? args))))))))
((branching-primitive? name)
(convert-args cps args
(lambda (cps args)
(with-cps cps
(let$ k (adapt-arity k src 1))
(letk kt ($kargs () () ($continue k src ($const #t))))
(letk kf ($kargs () () ($continue k src ($const #f))))
(build-term ($continue kf src
($branch kt ($primcall name args))))))))
((and (eq? name 'not) (match args ((_) #t) (_ #f)))
(convert-args cps args
(lambda (cps args)
(with-cps cps
(let$ k (adapt-arity k src 1))
(letk kt ($kargs () () ($continue k src ($const #f))))
(letk kf ($kargs () () ($continue k src ($const #t))))
(build-term ($continue kf src
($branch kt ($values args))))))))
((and (eq? name 'list)
(and-map (match-lambda
((or ($ <const>)
($ <void>)
($ <lambda>)
($ <lexical-ref>)) #t)
(_ #f))
args))
;; See note below in `canonicalize' about `vector'. The same
;; thing applies to `list'.
(with-cps cps
(let$ k (adapt-arity k src 1))
($ ((lambda (cps)
(let lp ((cps cps) (args args) (k k))
(match args
(()
(with-cps cps
(build-term ($continue k src ($const '())))))
((arg . args)
(with-cps cps
(letv tail)
(let$ body (convert-arg arg
(lambda (cps head)
(with-cps cps
(build-term
($continue k src
($primcall 'cons (head tail))))))))
(letk ktail ($kargs ('tail) (tail) ,body))
($ (lp args ktail)))))))))))
((prim-instruction name)
=> (lambda (instruction)
(define (box+adapt-arity cps k src out)
(case instruction
((bv-f32-ref bv-f64-ref)
(with-cps cps
(letv f64)
(let$ k (adapt-arity k src out))
(letk kbox ($kargs ('f64) (f64)
($continue k src ($primcall 'f64->scm (f64)))))
kbox))
((char->integer
string-length vector-length
bv-length bv-u8-ref bv-u16-ref bv-u32-ref bv-u64-ref)
(with-cps cps
(letv u64)
(let$ k (adapt-arity k src out))
(letk kbox ($kargs ('u64) (u64)
($continue k src ($primcall 'u64->scm (u64)))))
kbox))
((bv-s8-ref bv-s16-ref bv-s32-ref bv-s64-ref)
(with-cps cps
(letv s64)
(let$ k (adapt-arity k src out))
(letk kbox ($kargs ('s64) (s64)
($continue k src ($primcall 's64->scm (s64)))))
kbox))
(else
(adapt-arity cps k src out))))
(define (unbox-arg cps arg unbox-op have-arg)
(with-cps cps
(letv unboxed)
(let$ body (have-arg unboxed))
(letk kunboxed ($kargs ('unboxed) (unboxed) ,body))
(build-term
($continue kunboxed src ($primcall unbox-op (arg))))))
(define (unbox-args cps args have-args)
(case instruction
((bv-f32-ref bv-f64-ref
bv-s8-ref bv-s16-ref bv-s32-ref bv-s64-ref
bv-u8-ref bv-u16-ref bv-u32-ref bv-u64-ref)
(match args
((bv idx)
(unbox-arg
cps idx 'scm->u64
(lambda (cps idx)
(have-args cps (list bv idx)))))))
((bv-f32-set! bv-f64-set!)
(match args
((bv idx val)
(unbox-arg
cps idx 'scm->u64
(lambda (cps idx)
(unbox-arg
cps val 'scm->f64
(lambda (cps val)
(have-args cps (list bv idx val)))))))))
((bv-s8-set! bv-s16-set! bv-s32-set! bv-s64-set!)
(match args
((bv idx val)
(unbox-arg
cps idx 'scm->u64
(lambda (cps idx)
(unbox-arg
cps val 'scm->s64
(lambda (cps val)
(have-args cps (list bv idx val)))))))))
((bv-u8-set! bv-u16-set! bv-u32-set! bv-u64-set!)
(match args
((bv idx val)
(unbox-arg
cps idx 'scm->u64
(lambda (cps idx)
(unbox-arg
cps val 'scm->u64
(lambda (cps val)
(have-args cps (list bv idx val)))))))))
((vector-ref struct-ref string-ref)
(match args
((obj idx)
(unbox-arg
cps idx 'scm->u64
(lambda (cps idx)
(have-args cps (list obj idx)))))))
((vector-set! struct-set! string-set!)
(match args
((obj idx val)
(unbox-arg
cps idx 'scm->u64
(lambda (cps idx)
(have-args cps (list obj idx val)))))))
((make-vector)
(match args
((length init)
(unbox-arg
cps length 'scm->u64
(lambda (cps length)
(have-args cps (list length init)))))))
((allocate-struct)
(match args
((vtable nfields)
(unbox-arg
cps nfields 'scm->u64
(lambda (cps nfields)
(have-args cps (list vtable nfields)))))))
((integer->char)
(match args
((integer)
(unbox-arg
cps integer 'scm->u64
(lambda (cps integer)
(have-args cps (list integer)))))))
(else (have-args cps args))))
(convert-args cps args
(lambda (cps args)
;; Tree-IL primcalls are sloppy, in that it could be
;; that they are called with too many or too few
;; arguments. In CPS we are more strict and only
;; residualize a $primcall if the argument count
;; matches.
(match (prim-arity instruction)
((out . in)
(if (= in (length args))
(with-cps cps
(let$ k (box+adapt-arity k src out))
($ (unbox-args
args
(lambda (cps args)
(with-cps cps
(build-term
($continue k src
($primcall instruction args))))))))
(with-cps cps
(letv prim)
(letk kprim ($kargs ('prim) (prim)
($continue k src ($call prim args))))
(build-term ($continue kprim src ($prim name)))))))))))
(else
;; We have something that's a primcall for Tree-IL but not for
;; CPS, which will get compiled as a call and so the right thing
;; to do is to continue to the given $ktail or $kreceive.
(convert-args cps args
(lambda (cps args)
(with-cps cps
(build-term
($continue k src ($primcall name args)))))))))
;; Prompts with inline handlers.
(($ <prompt> src escape-only? tag body
($ <lambda> hsrc hmeta
($ <lambda-case> _ hreq #f hrest #f () hsyms hbody #f)))
;; Handler:
;; khargs: check args returned to handler, -> khbody
;; khbody: the handler, -> k
;;
;; Post-body:
;; krest: collect return vals from body to list, -> kpop
;; kpop: pop the prompt, -> kprim
;; kprim: load the values primitive, -> kret
;; kret: (apply values rvals), -> k
;;
;; Escape prompts evaluate the body with the continuation of krest.
;; Otherwise we do a no-inline call to body, continuing to krest.
(convert-arg cps tag
(lambda (cps tag)
(let ((hnames (append hreq (if hrest (list hrest) '())))
(bound-vars (map bound-var hsyms)))
(define (convert-body cps khargs krest)
(if escape-only?
(with-cps cps
(let$ body (convert body krest subst))
(letk kbody ($kargs () () ,body))
(build-term ($continue kbody src ($prompt #t tag khargs))))
(convert-arg cps body
(lambda (cps thunk)
(with-cps cps
(letk kbody ($kargs () ()
($continue krest (tree-il-src body)
($primcall 'call-thunk/no-inline
(thunk)))))
(build-term ($continue kbody (tree-il-src body)
($prompt #f tag khargs))))))))
(with-cps cps
(letv prim vals)
(let$ hbody (convert hbody k subst))
(let$ hbody (box-bound-vars hnames hsyms hbody))
(letk khbody ($kargs hnames bound-vars ,hbody))
(letk khargs ($kreceive hreq hrest khbody))
(letk kprim ($kargs ('prim) (prim)
($continue k src ($primcall 'apply (prim vals)))))
(letk kret ($kargs () ()
($continue kprim src ($prim 'values))))
(letk kpop ($kargs ('rest) (vals)
($continue kret src ($primcall 'unwind ()))))
;; FIXME: Attach hsrc to $kreceive.
(letk krest ($kreceive '() 'rest kpop))
($ (convert-body khargs krest)))))))
(($ <abort> src tag args ($ <const> _ ()))
(convert-args cps (cons tag args)
(lambda (cps args*)
(with-cps cps
(build-term
($continue k src ($primcall 'abort-to-prompt args*)))))))
(($ <abort> src tag args tail)
(convert-args cps
(append (list (make-primitive-ref #f 'abort-to-prompt) tag)
args
(list tail))
(lambda (cps args*)
(with-cps cps
(build-term ($continue k src ($primcall 'apply args*)))))))
(($ <conditional> src test consequent alternate)
(define (convert-test cps test kt kf)
(match test
(($ <primcall> src (? branching-primitive? name) args)
(convert-args cps args
(lambda (cps args)
(with-cps cps
(build-term ($continue kf src
($branch kt ($primcall name args))))))))
(($ <conditional> src test consequent alternate)
(with-cps cps
(let$ t (convert-test consequent kt kf))
(let$ f (convert-test alternate kt kf))
(letk kt* ($kargs () () ,t))
(letk kf* ($kargs () () ,f))
($ (convert-test test kt* kf*))))
(_ (convert-arg cps test
(lambda (cps test)
(with-cps cps
(build-term ($continue kf src
($branch kt ($values (test)))))))))))
(with-cps cps
(let$ t (convert consequent k subst))
(let$ f (convert alternate k subst))
(letk kt ($kargs () () ,t))
(letk kf ($kargs () () ,f))
($ (convert-test test kt kf))))
(($ <lexical-set> src name gensym exp)
(convert-arg cps exp
(lambda (cps exp)
(match (hashq-ref subst gensym)
((orig-var box #t)
(with-cps cps
(let$ k (adapt-arity k src 0))
(build-term
($continue k src ($primcall 'box-set! (box exp))))))))))
(($ <seq> src head tail)
(if (zero-valued? head)
(with-cps cps
(let$ tail (convert tail k subst))
(letk kseq ($kargs () () ,tail))
($ (convert head kseq subst)))
(with-cps cps
(let$ tail (convert tail k subst))
(letv vals)
(letk kseq ($kargs ('vals) (vals) ,tail))
(letk kreceive ($kreceive '() 'vals kseq))
($ (convert head kreceive subst)))))
(($ <let> src names syms vals body)
(let lp ((cps cps) (names names) (syms syms) (vals vals))
(match (list names syms vals)
((() () ()) (convert cps body k subst))
(((name . names) (sym . syms) (val . vals))
(with-cps cps
(let$ body (lp names syms vals))
(let$ body (box-bound-var name sym body))
($ ((lambda (cps)
(if (single-valued? val)
(with-cps cps
(letk klet ($kargs (name) ((bound-var sym)) ,body))
($ (convert val klet subst)))
(with-cps cps
(letv rest)
(letk klet ($kargs (name 'rest) ((bound-var sym) rest) ,body))
(letk kreceive ($kreceive (list name) 'rest klet))
($ (convert val kreceive subst))))))))))))
(($ <fix> src names gensyms funs body)
;; Some letrecs can be contified; that happens later.
(define (convert-funs cps funs)
(match funs
(()
(with-cps cps '()))
((fun . funs)
(with-cps cps
(let$ fun (convert fun k subst))
(let$ funs (convert-funs funs))
(cons (match fun
(($ $continue _ _ (and fun ($ $fun)))
fun))
funs)))))
(if (current-topbox-scope)
(let ((vars (map bound-var gensyms)))
(with-cps cps
(let$ body (convert body k subst))
(letk krec ($kargs names vars ,body))
(let$ funs (convert-funs funs))
(build-term ($continue krec src ($rec names vars funs)))))
(let ((scope-id (fresh-scope-id)))
(with-cps cps
(let$ body ((lambda (cps)
(parameterize ((current-topbox-scope scope-id))
(convert cps exp k subst)))))
(letk kscope ($kargs () () ,body))
($ (capture-toplevel-scope src scope-id kscope))))))
(($ <let-values> src exp
($ <lambda-case> lsrc req #f rest #f () syms body #f))
(let ((names (append req (if rest (list rest) '())))
(bound-vars (map bound-var syms)))
(with-cps cps
(let$ body (convert body k subst))
(let$ body (box-bound-vars names syms body))
(letk kargs ($kargs names bound-vars ,body))
(letk kreceive ($kreceive req rest kargs))
($ (convert exp kreceive subst)))))))
(define (build-subst exp)
"Compute a mapping from lexical gensyms to CPS variable indexes. CPS
uses small integers to identify variables, instead of gensyms.
This subst table serves an additional purpose of mapping variables to
replacements. The usual reason to replace one variable by another is
assignment conversion. Default argument values is the other reason.
The result is a hash table mapping symbols to substitutions (in the case
that a variable is substituted) or to indexes. A substitution is a list
of the form:
(ORIG-INDEX SUBST-INDEX BOXED?)
A true value for BOXED? indicates that the replacement variable is in a
box. If a variable is not substituted, the mapped value is a small
integer."
(let ((table (make-hash-table)))
(define (down exp)
(match exp
(($ <lexical-set> src name sym exp)
(match (hashq-ref table sym)
((orig subst #t) #t)
((orig subst #f) (hashq-set! table sym (list orig subst #t)))
((? number? idx) (hashq-set! table sym (list idx (fresh-var) #t)))))
(($ <lambda-case> src req opt rest kw inits gensyms body alternate)
(fold-formals (lambda (name sym init seed)
(hashq-set! table sym
(if init
(list (fresh-var) (fresh-var) #f)
(fresh-var))))
#f
(make-$arity req (or opt '()) rest
(if kw (cdr kw) '()) (and kw (car kw)))
gensyms
inits))
(($ <let> src names gensyms vals body)
(for-each (lambda (sym)
(hashq-set! table sym (fresh-var)))
gensyms))
(($ <fix> src names gensyms vals body)
(for-each (lambda (sym)
(hashq-set! table sym (fresh-var)))
gensyms))
(_ #t))
(values))
(define (up exp) (values))
((make-tree-il-folder) exp down up)
table))
(define (cps-convert/thunk exp)
(parameterize ((label-counter 0)
(var-counter 0)
(scope-counter 0))
(with-cps empty-intmap
(letv init)
;; Allocate kinit first so that we know that the entry point's
;; label is zero. This simplifies data flow in the compiler if we
;; can just pass around the program as a map of continuations and
;; know that the entry point is label 0.
(letk kinit ,#f)
(letk ktail ($ktail))
(let$ body (convert exp ktail (build-subst exp)))
(letk kbody ($kargs () () ,body))
(letk kclause ($kclause ('() '() #f '() #f) kbody #f))
($ ((lambda (cps)
(let ((init (build-cont
($kfun (tree-il-src exp) '() init ktail kclause))))
(with-cps (persistent-intmap (intmap-replace! cps kinit init))
kinit))))))))
(define *comp-module* (make-fluid))
(define %warning-passes
`((unused-variable . ,unused-variable-analysis)
(unused-toplevel . ,unused-toplevel-analysis)
(shadowed-toplevel . ,shadowed-toplevel-analysis)
(unbound-variable . ,unbound-variable-analysis)
(macro-use-before-definition . ,macro-use-before-definition-analysis)
(arity-mismatch . ,arity-analysis)
(format . ,format-analysis)))
(define (optimize-tree-il x e opts)
(define warnings
(or (and=> (memq #:warnings opts) cadr)
'()))
;; Go through the warning passes.
(let ((analyses (filter-map (lambda (kind)
(assoc-ref %warning-passes kind))
warnings)))
(analyze-tree analyses x e))
(optimize x e opts))
(define (canonicalize exp)
(post-order
(lambda (exp)
(match exp
(($ <primcall> src 'vector
(and args
((or ($ <const>) ($ <void>) ($ <lambda>) ($ <lexical-ref>))
...)))
;; Some macros generate calls to "vector" with like 300
;; arguments. Since we eventually compile to make-vector and
;; vector-set!, it reduces live variable pressure to allocate the
;; vector first, then set values as they are produced, if we can
;; prove that no value can capture the continuation. (More on
;; that caveat here:
;; http://wingolog.org/archives/2013/11/02/scheme-quiz-time).
;;
;; Normally we would do this transformation in the compiler, but
;; it's quite tricky there and quite easy here, so hold your nose
;; while we drop some smelly code.
(let ((len (length args))
(v (gensym "v ")))
(make-let src
(list 'v)
(list v)
(list (make-primcall src 'make-vector
(list (make-const #f len)
(make-const #f #f))))
(fold (lambda (arg n tail)
(make-seq
src
(make-primcall
src 'vector-set!
(list (make-lexical-ref src 'v v)
(make-const #f n)
arg))
tail))
(make-lexical-ref src 'v v)
(reverse args) (reverse (iota len))))))
(($ <primcall> src 'struct-set! (struct index value))
;; Unhappily, and undocumentedly, struct-set! returns the value
;; that was set. There is code that relies on this. Hackety
;; hack...
(let ((v (gensym "v ")))
(make-let src
(list 'v)
(list v)
(list value)
(make-seq src
(make-primcall src 'struct-set!
(list struct
index
(make-lexical-ref src 'v v)))
(make-lexical-ref src 'v v)))))
;; Lower (logand x (lognot y)) to (logsub x y). We do it here
;; instead of in CPS because it gets rid of the lognot entirely;
;; if type folding can't prove Y to be an exact integer, then DCE
;; would have to leave it in the program for its possible
;; effects.
(($ <primcall> src 'logand (x ($ <primcall> _ 'lognot (y))))
(make-primcall src 'logsub (list x y)))
(($ <primcall> src 'logand (($ <primcall> _ 'lognot (y)) x))
(make-primcall src 'logsub (list x y)))
(($ <prompt> src escape-only? tag body
($ <lambda> hsrc hmeta
($ <lambda-case> _ hreq #f hrest #f () hsyms hbody #f)))
exp)
;; Eta-convert prompts without inline handlers.
(($ <prompt> src escape-only? tag body handler)
(let ((h (gensym "h "))
(args (gensym "args ")))
(make-let
src (list 'h) (list h) (list handler)
(make-seq
src
(make-conditional
src
(make-primcall src 'procedure? (list (make-lexical-ref #f 'h h)))
(make-void src)
(make-primcall
src 'scm-error
(list
(make-const #f 'wrong-type-arg)
(make-const #f "call-with-prompt")
(make-const #f "Wrong type (expecting procedure): ~S")
(make-primcall #f 'list (list (make-lexical-ref #f 'h h)))
(make-primcall #f 'list (list (make-lexical-ref #f 'h h))))))
(make-prompt
src escape-only? tag body
(make-lambda
src '()
(make-lambda-case
src '() #f 'args #f '() (list args)
(make-primcall
src 'apply
(list (make-lexical-ref #f 'h h)
(make-lexical-ref #f 'args args)))
#f)))))))
(_ exp)))
exp))
(define (compile-cps exp env opts)
(values (cps-convert/thunk
(canonicalize (optimize-tree-il exp env opts)))
env
env))
;;; Local Variables:
;;; eval: (put 'convert-arg 'scheme-indent-function 2)
;;; eval: (put 'convert-args 'scheme-indent-function 2)
;;; End:
| false |
290ad3a78ef17310913799ccf5808e4656dd9270
|
951b7005abfe3026bf5b3bd755501443bddaae61
|
/迭代式改进.scm
|
7a8397e62b6cf5a60fad5db79a520273cc7e1ae4
|
[] |
no_license
|
WingT/scheme-sicp
|
d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61
|
a255f3e43b46f89976d8ca2ed871057cbcbb8eb9
|
refs/heads/master
| 2020-05-21T20:12:17.221412 | 2016-09-24T14:56:49 | 2016-09-24T14:56:49 | 63,522,759 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 606 |
scm
|
迭代式改进.scm
|
(define (iterative-improve good-enough? improve)
(lambda (x) (define (iter guess)
(if (good-enough? guess)
guess
(iter (improve guess))))
(iter x)))
(define (squareroot x)
(define (improve y)
(/ (+ y (/ x y)) 2.0))
(define (good-enough? guess)
(< (abs (- guess (improve guess))) 0.00001))
((iterative-improve good-enough? improve) 1.0))
(squareroot 2)
(define (fixed-point f)
(define (good-enough? x)
(< (abs (- x (f x))) 0.00001))
((iterative-improve good-enough? f) 1.0))
(fixed-point (lambda (x) (+ 1 (/ 1 x))))
| false |
41ba974a992f3e589de36165a97b8872d083fb17
|
51d30de9d65cc3d5079f050de33d574584183039
|
/plist-demo.scm
|
c0c6fbd57fb05a1c8045aefb2800d516bbb514b2
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
langmartin/ykk
|
30feb00265d603ef765b5c664d2f759be34b7b89
|
dd6e441dddd5b6363ee9adbbdd0f346c1522ffcf
|
refs/heads/master
| 2016-09-05T20:01:19.353224 | 2009-12-10T16:25:55 | 2009-12-10T16:25:55 | 408,478 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 18,983 |
scm
|
plist-demo.scm
|
;;;; "Type Tree"
(define-record-type/primitive :folder
nongenerative: ua8db299f-732b-4947-ba86-074e4a384bba
(sticky (type :boolean)))
(define-record-type/primitive :person
nongenerative: u2a019585-f45a-4ea9-9001-ee1186d9df51
(name (type :string))
(age (type :number))
(gender (type :symbol)))
(define-record-type/primitive :place
nongenerative: ufb76a3cd-903c-413f-86a0-3f36e74513c2
(address (type :string))
(city (type :string))
(state (type :symbol))
(zip (type :string)))
(define-record-type/primitive :thing
nongenerative: u5ac8fe2a-0a7a-475f-a336-d3441cc1517d
(color (type :string))
(weight (type :number))
(texture (type :symbol)))
(define-syntax ref-table
(syntax-rules ()
((_ item ...)
(list (cons 'item item) ...))))
(define *allow-types*
(ref-table :folder :person :place :thing))
(define (lookup-type name)
(alist-ref *allow-types* name))
(define (type-options)
(map-in-order (compose symbol->string car) *allow-types*))
(define (type->option type)
(cond ((find (predicate-eq cdr type) *allow-types*) => car)
(else #f)))
;;;; Top
(define (persist-once name thunk)
(if (not (persistent-symbol name))
(persistent-symbol-set! name (thunk))))
(define (top)
(persistent-symbol 'top))
(define (scanned-top)
(scan (top)))
(define (update-scanned-top new-top)
(persistent-symbol-set!
'top
(scanned->source new-top))
new-top)
(persist-once
'top
(lambda ()
(source:root (source:node :folder
(plist (sticky #f))))))
;; (persistent-symbol-set!
;; 'top
;; (source:root (source:node :folder
;; (plist (sticky #f)))))
;;;; Manipulation
(define (zip-up/update-top z)
(update-scanned-top
(zip-all-the-way-up z)))
(define (perform op z)
(zip-up/update-top
(move 'up (op (z-item z)) z)))
(define (perform/go op z href-proc)
;; FIXME: this might as well be a destructive operation at this
;; point... how do we use it functionally?
(perform op z)
(see-other (href-proc "")))
(define (perform/path op p)
(perform op (resolve (scanned-top) p)))
(define (insert g child)
(replace-children
g
(add-child child (graph-children g))))
(define (source:update-source node new-source)
(sharing-record-update node source::node (code new-source)))
(define (update-source g new-source)
(replace-node
g
(source:update-source
(source:graph-node (scanned->source g))
new-source)))
;;;; Plist Utilities
;;;; Path Utilities
(define (list->absolute-path p)
(make-absolute (list->path p)))
(define (list->path p)
(map-in-order (compose string->symbol obj->path-segment) p))
(define (join-path . segments)
(string-join (map-in-order obj->path-segment segments) "/"))
(define (obj->path-segment obj)
(cond ((string? obj)
(string-trim-right obj #\/))
((symbol? obj)
(obj->path-segment (symbol->string obj)))
((number? obj)
(obj->path-segment (number->string obj 10)))
((not obj)
"")
(else
(error 'wrong-type-argument
"obj->path-segment: expecting string, symbol, number, or #f"
obj))))
(define (name->string name)
(cond ((symbol? name) (symbol->string name))
((not name) "")
(else
(error 'wrong-type-argument
"name->string: expecting symbol or #f"))))
(assert (list->absolute-path '("foo" "bar")) => '(#f foo bar))
(assert (name->string #f) => "")
(assert (name->string 'foo) => "foo")
;;;; Other Utilities
(define (set-parameters path params)
(let ((path old-params (parse-url-path path)))
(add-parameters-to-path
path
(merge-alists proj-1 old-params params))))
(define (add-parameters-to-path path params)
(let-string-output-port
(output path #\?)
(for-each (lambda (p)
(if (pair? p)
(begin
(display-urlencode (car p))
(display #\=)
(display-urlencode (cdr p)))
(display p)))
(intersperse #\& params))))
(define (display-urlencode s)
(with-current-input-port
(value->input-port s)
(lambda ()
(for-each-display (urlencode read-char)))))
(define (value->input-port v)
(cond ((input-port? v)
v)
((string? v)
(make-string-input-port v))
(else
(make-string-input-port
(let-string-output-port (display v))))))
(define (output->string . stream)
(let-string-output-port
(apply output stream)))
;;;; Testing
(define-syntax* (simulate-request
(url: url "http://localhost/")
(query: query '())
(method: method "get")
(headers: headers '())
. body)
(with-request
(make-request "HTTP/1.1" method (parse-url url) query headers)
(lambda ()
(output->string . body))))
;;;; Infrastructure
(define-syntax* (response
(status: status 200)
(type: content-type "text/html")
(headers: headers ())
(around-body: around identity)
body)
(expand-response status content-type headers (around body)))
(define-syntax expand-response
(lambda (form rename compare)
(let ((status (cadr form))
(type (caddr form))
(headers (map-car desyntaxify (cadddr form)))
(body (cadr (cdddr form))))
(define %let-http-response (rename 'let-http-response))
(define %let-headers (rename 'let-headers))
(define %let-content-vector (rename 'let-content-vector))
(define %status-code->phrase (rename 'status-code->phrase))
(define (all-headers)
(if (assq 'content-type headers)
headers
(cons (list 'content-type type)
headers)))
(define (status-line)
(cond ((pair? status)
status)
((or (number? status) (string? status))
(list status (status-code->phrase status)))
(else
`(,status (,%status-code->phrase ,status)))))
`(,%let-http-response ,(status-line)
(,%let-headers ,(all-headers)
(,%let-content-vector ,body))))))
(define-condition
%make-reset-page (error)
reset-page?)
(define (make-reset-page thunk)
(%make-reset-page thunk))
(define (reset-page-thunk c)
(car (condition-stuff c)))
(define (call-with-page-reset-extent thunk)
(with-exception-catcher
handle-reset-page
thunk))
(define (handle-reset-page c prop)
(if (reset-page? c)
((reset-page-thunk c))
(prop)))
(define-syntax in-reset-extent
(syntax-rules ()
((_ body)
(call-with-page-reset-extent
(lambda () body)))))
(define-syntax page
(syntax-rules ()
((_ . arguments)
(in-reset-extent
(response
around-body: shtml->html
. arguments)))))
(define-syntax reset-page
(syntax-rules ()
((_ . arguments)
(make-reset-page
(lambda () (page . arguments))))))
(define (method-not-allowed . allowed)
(let ((allowed (string-join (map symbol->string allowed) " ")))
(reset-page
status: 405
headers: ((allowed allowed))
(method-not-allowed-page (request-method) allowed))))
(define (method-not-allowed-page method allowed)
(http-error-template
405
`(p ,method " is not allowed."
" Allowed methods are: " ,allowed)))
(define (bad-request . message)
(apply reset/simple-error-page 400 message))
(define (reset/simple-error-page code . message)
(reset/error-page
code
(apply output->string (intersperse #\space message))))
(define (reset/error-page code explaination)
(reset-page
status: code
(http-error-template code `(p ,explaination))))
(define (error-page code explaination)
(page
status: code
(http-error-template code `(p ,explaination))))
(define (http-error-template code . body)
(let ((phrase (status-code->phrase code)))
`(html
(head
(title ,phrase))
(body
(h1 ,(number->string code 10) ": " ,phrase)
,@body))))
;; --------------------
;; Tests
(let ((simulate (lambda (method)
(simulate-request
method: method
(page
(method-case
((get) "success")))))))
(assert (simulate "get") =>
(output->string
(page "success")))
(assert (simulate "post") =>
(output->string
(page
status: 405
headers: ((allowed "get"))
(method-not-allowed-page "post" "get")))))
;;;; Resources
(define-syntax define-resource
(syntax-rules ()
((_ path handler)
(http-register-page! path handler))))
(define-syntax define-resolving-resource
(syntax-rules ()
((_ (path . formals) body ...)
(define-resource path
(call-handler/resolved-cursor
'()
(lambda formals
body ...))))))
(define (call-handler/resolved-cursor root handler)
(let ((root (list->absolute-path root)))
(lambda path
(safe-call/resolved
handle-path-error
(scanned-top)
(append root path)
handler))))
(define (safe-call/resolved handle-error z path success)
(with-exception-catcher
(lambda (c prop)
(if (path-error? c)
(handle-error c)
(prop)))
(lambda ()
(success (resolve z path) path))))
(define (handle-path-error c)
(cond ((path-does-not-exist? c)
(error-page 404 "Path does not exist."))
(else
(error-page 500 "Unrecognized path error."))))
(define (path-does-not-exist? c)
(and (path-error? c)
(condition-stuff-car-is? c 'path-does-not-exist)))
(define (condition-stuff-car-is? c maybe)
(eq? (car (condition-stuff c)) maybe))
(define (see-other href)
(reset-page
status: 303
headers: ((location href))
""))
(begin
(assert (safe-call/resolved never? (scanned-top) '(foozle) proj-0) => #f)
(assert (graph-zipper? (safe-call/resolved never? (scanned-top) '(#f) proj-0)))
)
;;;;
(define (header/footer-wind thunk)
(page
`(html
(head
(title "Plist Editor")
,(css "/static/reset-fonts-grids-base.css")
,(css "/static/plist.css"))
(body
(div (@ (id "doc"))
(div (@ (id "hd"))
(h1 "Plist Editor"))
(div (@ (id "bd")) ,(thunk))
(div (@ (id "ft"))))))))
(define (css href)
`(link (@ (rel "stylesheet")
(type "text/css")
(href ,href))))
(define (nav-list attributes items)
`(ul ,(add-class attributes "nav-list")
,@(map-in-order make-nav-list-item items)))
(define (make-nav-list-item item)
(let ((name href (unlist item)))
`(li (a (@ (href ,href))
,name))))
(define (new-item-href href)
(set-parameters href '((new . true))))
(define (parameterized-request-path)
(set-parameters (request-path) (get-parameters)))
;; --------------------
;; Data Tree
(define-resolving-resource ("/data" z path)
(header/footer-wind
(lambda ()
(method-case
((get)
(tree->shtml (z-item z) (apply join-path path)))))))
(define (tree->shtml tree path)
`(ul (@ (class "data-tree"))
(p (@ (class "item"))
(a (@ (href ,(plist-editor-href path)))
,(plist-title tree)))
,(if (leaf? tree)
`(p (@ (class "leaf")))
`(div (@ (class "children"))
,@(map-children
(lambda (z)
(tree->shtml
tree
(join-path path (graph-name tree))))
tree)))))
(define (map-children proc g)
(fold-children (lambda (c acc)
(cons (proc c) acc))
(graph-children g)))
(define (plist-editor-href rel)
(join-path "/plist" rel))
(define (data-tree-href rel)
(join-path "/data" rel))
;; --------------------
;; Plist Editor
(define-resolving-resource ("/plist" z path)
(header/footer-wind
(lambda ()
(let ((path (apply join-path path)))
(method-case
((get) (get-plist z))
((post) (post-plist z)))))))
(define (get-plist z)
(let* ((item (z-item z))
(new type (bind-alist (new type) (get-parameters)))
(title (plist-title item)))
(cond (new
(new-plist-item-form
title (and type (request-environment-ref type))))
(else
(plist-form
title (graph-type item) (graph-forms item) '())))))
(define (post-plist path z)
(let* ((item (z-item z))
(type (graph-type item))
(relevant-data (schemify-parameters (remove-parameters 'do-save)))
(good errors (validate-plist-data type relevant-data)))
(if (null? errors)
(perform/go (cut update-source <> `(plist ,@(map-in-order pair->list good)))
z data-tree-href)
(plist-form path (plist-title item) type relevant-data errors))))
(define (string->form s)
(let-string-input-port s (read)))
(define schemify-parameters
(cute map-in-order (cut fmap-cdr string->form <>) <>))
(define (request-environment-ref name)
(with-exception-catcher
(lambda (c prop)
(if (unbound-variable-error? c)
(bad-request "undefined value" name)
(prop)))
(lambda ()
(environment-ref (interaction-environment) name))))
(define (unbound-variable-error? c)
(and (error? c)
(string=? "unbound variable" (car (condition-stuff c)))))
(define (validate-plist-data type data)
(let ((slots (rtd-slots type)))
(let loop ((data data) (good '()) (errors '()))
(cond ((null? data)
(values (reverse good) (reverse errors)))
((specification-of slots (caar data)) =>
(lambda (spec)
(let ((name value (uncons (car data)))
(type (specification-type spec)))
(if (scheme-form-conforms-to-type? type value)
(loop (cdr data)
(cons (car data) good)
errors)
(loop (cdr data)
good
(alist-cons name (data-does-not-conform-to-type-error-message type name value)
errors))))))
(else
(loop (cdr data)
(cons (car data) good)
errors))))))
(define (specification-type spec)
(cond ((get-specification-attribute spec 'type eq?) => attribute-value)
(else #f)))
(define (data-does-not-conform-to-type-error-message type name value)
(let-string-output-port
(output "The value of " name " does not conform to type " (type-name type))))
(define (plist-form title type data errors)
`(div (@ (id "plist-editor"))
,(form->shtml
`(form (@ (action ,(request-path))
(method "post"))
,(form-errors->shtml errors)
(fieldset
(legend "Editing: " ,title)
(ul (@ (class "plist-items"))
,@(map (render-plist-entry type) data)))
(div (@ (class "buttons"))
,(button-anchor `(@ (href ,(new-item-href (parameterized-request-path))))
"New Item")
(submit (@ (name "do-save")
(value "Save")))
(submit (@ (name "_method")
(value "Delete"))))))))
(define (new-plist-item-form title type)
`(div (@ (id "new-item-form"))
,(form->shtml
`(form (@ (action ,(request-path))
(method "get"))
,@(all-parameters->hidden-inputs)
(fieldset
(legend "New Item In: " ,title)
(ul (@ (class "new-item-inputs"))
,(apply list-field
maybe-select
`(@ (label "Type")
(default ,(type->option type)))
(type-options))))))))
(define (list-field make-field attributes . rest)
(let* ((label name rest (pluck-attributes (label name) attributes))
(label (or label (string->label name)))
(name (or name (string->name label))))
`(li (@ (class ,(join-classes "field" (string->identifier label))))
(label (@ (for ,name)) ,label)
,(apply make-field
(update-attributes rest `((name ,name)))
rest))))
(define (maybe-select attributes . options)
(let ((submitted default (bind-attributes (submitted default) attributes)))
(if )))
(define (all-parameters->hidden-inputs)
(reverse
(fold parameter->hidden-input
(fold parameter->hidden-input
'()
(request-parameters))
(get-parameters))))
(define (parameter->hidden-input param inputs)
(cons `(input (@ (type "hidden")
(name ,(maybe-symbol->string (car param)))
(values ,(cdr param))))
inputs))
(define (maybe-symbol->string obj)
(cond ((string? obj)
obj)
((symbol? obj)
(symbol->string obj))
(else
(error 'wrong-type-argument
"maybe-symbol->string: expecting string or symbol"
obj))))
(define (button-anchor attributes name)
(let ((href attributes (pluck-spec (href) (cdr attributes))))
`(input ,(update-attributes
`(@ (value ,name)
(type "button")
(onclick ,(string-append "document.location.href='" href "';")))
attributes))))
(define (form-errors->shtml errors)
(if (null? errors)
""
`(ul (@ (class "form-errors"))
,@(map-in-order
(lambda (e)`(li ,(cdr e)))
errors))))
(define-generic plist-title &plist-title (item))
(define-method &plist-title ((item :graph))
(if (root? item)
"/"
(name->string (graph-name item))))
(define-method &plist-title ((item :graph-zipper))
(plist-title (z-item item)))
(define (render-plist-entry type)
(lambda (entry)
(let ((name value (uncons entry)))
`(li (@ (class ,(classify-plist-entry name value)))
,(label-plist-entry name value)
,(render-plist-input name value)))))
(define (classify-plist-entry name value)
"simple")
(define (label-plist-entry name value)
(let ((string-name (symbol->string name)))
`(label (@ (for ,string-name))
,string-name ": ")))
(define (render-plist-input name value)
(let ((string-name (symbol->string name)))
`(text (@ (name ,string-name)
(default ,(plist-value->attribute-value value))))))
(define (plist-value->attribute-value v)
(concat v))
(define (choose-parameters names)
(choose-keys names (request-parameters)))
(define (remove-parameters names)
(remove-keys names (request-parameters)))
| true |
4acd2b014557c0a25c34d9f738b43d2f2049b0fd
|
d8bdd07d7fff442a028ca9edbb4d66660621442d
|
/scam/tests/20-scam/class/call-base.scm
|
8da5bac39657b11f1fa67aa2df95e80f1555f986
|
[] |
no_license
|
xprime480/scam
|
0257dc2eae4aede8594b3a3adf0a109e230aae7d
|
a567d7a3a981979d929be53fce0a5fb5669ab294
|
refs/heads/master
| 2020-03-31T23:03:19.143250 | 2020-02-10T20:58:59 | 2020-02-10T20:58:59 | 152,641,151 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 293 |
scm
|
call-base.scm
|
(import (only (scam class) make-class)
(test narc))
(narc-label "Call Parent Function Parent Directly")
(define Parent
(make-class
Root
()
(get () -1)))
(define Trivial
(make-class
Parent
()))
(define obj (Trivial))
(narc-expect
(-1 (obj get)))
(narc-report)
| false |
c69b73c83de6568b6ef6dc3c6daca1d084ace751
|
23a00b9f5709b38169e0514cd3965d8b6f1f3863
|
/lib/compiler/reader/scanner/scanner.scm
|
e298fd4ca213037e3ec4d49e0ba38cb6b4b867f5
|
[] |
no_license
|
uson-compiladores/r7rs-scheme
|
cd80812ed335fa24e78522005df95ccdfbb544c4
|
dd88b31b260687aa9c702b659d54a7a3f60c7047
|
refs/heads/master
| 2021-01-10T02:09:16.711983 | 2015-12-01T01:04:56 | 2015-12-01T01:04:56 | 45,621,985 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 435 |
scm
|
scanner.scm
|
(define (scanner-make port)
(define (scan c)
(if (eof-object? c)
(delay (cons c '()))
(delay (cons c (scan (read-char port))))))
(scan (read-char port)))
(define (scanner-read scanner)
(car (force scanner)))
(define (scanner-next scanner)
(cdr (force scanner)))
(define (scanner->list scanner)
(define c (scanner-read scanner))
(if (eof-object? c)
'()
(cons c (scanner->list (scanner-next scanner)))))
| false |
9948104da77f79a206d274281944b93255ff4894
|
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
|
/src/ws/langs/lang32_emit-nesc.ss
|
27b0030d85b4f8e56683e518521ccbef32ba854c
|
[
"BSD-3-Clause"
] |
permissive
|
rrnewton/WaveScript
|
2f008f76bf63707761b9f7c95a68bd3e6b9c32ca
|
1c9eff60970aefd2177d53723383b533ce370a6e
|
refs/heads/master
| 2021-01-19T05:53:23.252626 | 2014-10-08T15:00:41 | 2014-10-08T15:00:41 | 1,297,872 | 10 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 114 |
ss
|
lang32_emit-nesc.ss
|
(define emit-nesc-language
(lambda (prog) (emit/compile-nesc prog)))
;; I'm moving this code to tossim.ss ^^
| false |
5fac5b0adabbe4bc1ef86dd55f1b8c84fac64e99
|
557c51d080c302a65e6ef37beae7d9b2262d7f53
|
/workspace/comp-tester/tests/test15.ss
|
19ba433e0c1bfcd28c0cd720d6824397dd611bc6
|
[] |
no_license
|
esaliya/SchemeStack
|
286a18a39d589773d33e628f81a23bcdd0fc667b
|
dcfa1bbfa63b928a7ea3fc244f305369763678ad
|
refs/heads/master
| 2020-12-24T16:24:08.591437 | 2016-03-08T15:30:37 | 2016-03-08T15:30:37 | 28,023,003 | 3 | 4 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 320 |
ss
|
test15.ss
|
;;-----------------------
;; Saliya Ekanayake
;; sekanaya
;; Test15
;;-----------------------
;; CPS style factorial
(letrec ([fact-cps (lambda (n k)
(if (eq? n 0)
(k 1)
(fact-cps (- n 1) (lambda (v) (k (* n v))))))])
(fact-cps 5 (lambda (k) k)))
| false |
fbe33ff9cc16c3bf921381e076c9813291e92cea
|
f7dc6abdd30bf5623624073ffe63027bb07dc7d8
|
/eggs/hyde/hyde-atom.scm
|
97fc9dfd194d5866a011abb29992d1cc05108324
|
[] |
no_license
|
kobapan/scheme-chicken-hyde
|
9539bd0cb4e9e1b3775e89e3f042ce4131a485a5
|
2b0d7a7d6f213646d4736a123d62f6247c04d096
|
refs/heads/main
| 2023-04-30T01:10:31.839459 | 2021-05-18T11:40:19 | 2021-05-18T11:40:19 | 316,645,212 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,304 |
scm
|
hyde-atom.scm
|
(include "backwards-compatible-module")
(backwards-compatible-module (hyde atom)
(translate-atom)
(import scheme)
(cond-expand
(chicken-4
(import chicken)
(use hyde atom rfc3339 posix extras srfi-1))
(chicken-5
(import (chicken base)
(chicken format)
(chicken time posix)
(srfi 1)
hyde
atom
rfc3339)))
(define $ (environment-ref (page-eval-env) '$))
(define (maybe-authors->atom-authors authors)
(if authors
(map (lambda (author)
(make-author name: author))
authors)
'()))
(define (pages->atom-doc pages #!key
(page-title (lambda (page) ($ 'title page)))
(page-date (lambda (page)
(or ($ 'updated page) ($ 'date page))))
(page-type (lambda (page)
($ 'type page)))
(page-authors (lambda (page)
($ 'authors page)))
(page-date->rfc3339-string (lambda (x) x))
(page->atom-content (lambda (page)
(make-content (read-page page) type: 'html))))
(unless (and ($ 'tag) ($ 'base-uri) ($ 'date))
(error "An atom page requires at least these page-vars to be defined"
'(tag base-uri date)))
(let* ((rfc3339-string->seconds
(lambda (date)
(rfc3339->seconds (string->rfc3339 date))))
(page-date->seconds
(lambda (date)
(rfc3339-string->seconds (page-date->rfc3339-string date))))
(rfc3339-string->YYYY-MM-DD
(lambda (date)
(time->string (seconds->utc-time (rfc3339-string->seconds date))
"%Y-%m-%d")))
(page-date->YYYY-MM-DD
(lambda (date)
(rfc3339-string->YYYY-MM-DD (page-date->rfc3339-string date))))
(feed-authors (maybe-authors->atom-authors ($ 'authors))))
(make-atom-doc
(make-feed
title: (make-title ($ 'title))
subtitle: (make-subtitle ($ 'subtitle))
icon: (and ($ 'icon) (make-icon (string-append ($ 'base-uri) ($ 'icon))))
logo: (and ($ 'logo) (make-logo (string-append ($ 'base-uri) ($ 'logo))))
authors: feed-authors
updated: (rfc3339->string
(seconds->rfc3339
(fold (lambda (p c)
(let ((p (page-date->seconds (page-date p))))
(if (and c (> c p)) c p)))
#f
pages)))
id: (format ($ 'tag) ($ 'date) "/")
links: (list (make-link uri: (string-append ($ 'base-uri) (or ($ 'root-path) "/"))
relation: "alternate"
type: 'html)
(make-link uri: (string-append ($ 'base-uri) (page-path (current-page)))
relation: "self"
type: 'atom))
entries: (map (lambda (p)
(make-entry title: (make-title (page-title p))
published: (page-date->rfc3339-string (page-date p))
updated: (page-date->rfc3339-string (page-date p))
id: (format ($ 'tag)
(page-date->YYYY-MM-DD (page-date p))
(page-path p))
links: (list (make-link uri: (string-append ($ 'base-uri) (page-path p))
type: (or (page-type p) ($ 'entries-type))))
authors: (let ((authors (maybe-authors->atom-authors (page-authors p))))
;; we include the feed authors for every entry in case there are
;; none for this entry specifically since feed readers tend to ignore
;; feed-wide authors
(if (null? authors) feed-authors authors))
content: (page->atom-content p)))
pages)))))
(define (translate-atom)
(let ((env (page-eval-env)))
(for-each (lambda (binding)
(environment-set! env (car binding) (cadr binding)))
`((make-atom-doc ,make-atom-doc) (make-author ,make-author) (make-category ,make-category)
(make-content ,make-content) (make-contributor ,make-contributor) (make-entry ,make-entry)
(make-feed ,make-feed) (make-generator ,make-generator) (make-icon ,make-icon)
(make-link ,make-link) (make-logo ,make-logo) (make-rights ,make-rights)
(make-source ,make-source) (make-subtitle ,make-subtitle) (make-summary ,make-summary)
(make-title ,make-title) (make-rfc3339 ,make-rfc3339) (rfc3339->string ,rfc3339->string)
(seconds->rfc3339 ,seconds->rfc3339) (utc-time->rfc3339 ,utc-time->rfc3339)
(time->rfc3339 ,time->rfc3339) (pages->atom-doc ,pages->atom-doc)))
(write-atom-doc (environment-eval (read) env))))
(translators (cons (list "atom" translate-atom '(ext . atom) '(layouts))
(translators)))
)
| false |
b5d73c68453be6655aa0e15d68e3ba44db11fbb8
|
bde67688a401829ffb4a5c51394107ad7e781ba1
|
/test-tlex.scm
|
c47c41b47043f3b828eb95c17aeeada5eb95e4ff
|
[] |
no_license
|
shkmr/taco
|
1fad9c21284e12c9aae278f2e06de838363c3db9
|
8bbea1a4332d6d6773a3d253ee6c2c2f2bcf2b05
|
refs/heads/master
| 2021-01-10T03:50:55.411877 | 2016-08-11T03:37:53 | 2016-08-11T03:37:53 | 48,963,008 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,580 |
scm
|
test-tlex.scm
|
(use gauche.test)
(test-start "tlex")
(use tlex)
(test-module 'tlex)
(define *eof* (with-input-from-string "" read-char))
(define (run-lexer)
(guard (e ((is-a? e <error>)
(cons 'ERROR (ref e 'message)))
(else
(error "Unexpected exception")))
(port-map (lambda (x) x)
(lambda ()
(let ((x (tlex)))
(if (eq? x '*eoi*)
*eof*
x))))))
(define (test-tlex in expect)
(test* in expect (with-input-from-string in run-lexer)))
;;
;; TESTS START HERE
;;
;;
;; CARM 2.3 TOKENS
;;
(test-section "CARM 2.3 tokens")
(test-tlex "forwhile;" '((IDENTIFIER . forwhile) SEMICOLON))
(test-tlex "b>x;" '((IDENTIFIER . b) > (IDENTIFIER . x) SEMICOLON))
(test-tlex "b->x;" '((IDENTIFIER . b) PTR_EXTENT (IDENTIFIER . x) SEMICOLON))
(test-tlex "b--x;" '((IDENTIFIER . b) MINUSMINUS (IDENTIFIER . x) SEMICOLON))
(test-tlex "b---x;" '((IDENTIFIER . b) MINUSMINUS - (IDENTIFIER . x) SEMICOLON))
;;
;; integer constants
;;
(test-section "integer constants")
(test-tlex "1234;" '((CONSTANT int 1234) SEMICOLON))
(test-tlex "012;" '((CONSTANT int 10) SEMICOLON))
(test-tlex "0x12;" '((CONSTANT int 18) SEMICOLON))
;;
;; character constants
;;
(test-section "character constants")
(test-tlex "'a';" '((CONSTANT int "97") SEMICOLON))
(test-tlex "'A';" '((CONSTANT int "65") SEMICOLON))
(test-tlex "' ';" '((CONSTANT int "32") SEMICOLON))
(test-tlex "'?';" '((CONSTANT int "63") SEMICOLON))
(test-tlex "'\\r';" '((CONSTANT int "13") SEMICOLON))
(test-tlex "'\\0';" '((CONSTANT int "0") SEMICOLON))
(test-tlex "'\"';" '((CONSTANT int "34") SEMICOLON))
;; "255" or "-1", depending on the size of char
(test-tlex "'\\377';" '((CONSTANT int "255") SEMICOLON))
(test-tlex "'%';" '((CONSTANT int "37") SEMICOLON))
(test-tlex "'\\23';" '((CONSTANT int "19") SEMICOLON))
(test-tlex "'8';" '((CONSTANT int "56") SEMICOLON))
(test-tlex "'\\\\';" '((CONSTANT int "92") SEMICOLON))
;; (string->number "41424344" 16) -> 1094861636
(test-tlex "'ABCD';" '((CONSTANT int "1094861636") SEMICOLON))
;;
;; floating point constants
;;
(test-section "floating point constants")
(test-tlex "0.;" '((CONSTANT double 0.0) SEMICOLON))
(test-tlex "3e1;" '((CONSTANT double 3e1) SEMICOLON))
(test-tlex "3.14159;" '((CONSTANT double 3.14159) SEMICOLON))
(test-tlex ".0;" '((CONSTANT double 0.0) SEMICOLON))
(test-tlex "1.0E-3;" '((CONSTANT double 1.0E-3) SEMICOLON))
(test-tlex "1e-3;" '((CONSTANT double 1e-3) SEMICOLON))
(test-tlex "1.0;" '((CONSTANT double 1.0) SEMICOLON))
(test-tlex "0.00034;" '((CONSTANT double 0.00034) SEMICOLON))
(test-tlex "2e+9;" '((CONSTANT double 2e+9) SEMICOLON))
;; STDC floating point
(test-tlex "1.0f;" '((CONSTANT float 1.0) SEMICOLON))
(test-tlex "1.0e67L;" '((CONSTANT long-double 1.0e67) SEMICOLON))
(test-tlex "0E1L;" '((CONSTANT long-double 0E1) SEMICOLON))
(test-tlex "0x1.0p1;" '((CONSTANT double "1.0p1") SEMICOLON)) ; FIXEME!!
(test-tlex "0x1.0;" '(ERROR . "hexadecimal floating constant requires an exponent"))
;;
;; string constants
;;
(test-section "string constants")
(test-tlex "\"\";" '((STRING . "") SEMICOLON))
(test-tlex "\"\\\"\";" '((STRING . "\"") SEMICOLON))
(test-tlex "\"Copyright 2000 \\\nTexas Instruments. \""
'((STRING . "Copyright 2000 Texas Instruments. ")))
(test-tlex "\"Comments begin with '/*'.\\n\""
'((STRING . "Comments begin with '/*'.\n")))
(test-tlex "1.37E+6L;" '((CONSTANT long-double 1.37E+6) SEMICOLON) )
(test-tlex "\"String \"\"FOO\"\"\"" '((STRING . "String ") (STRING . "FOO") (STRING . "")) )
(test-tlex "\"Strinng+\\\"FOO\\\"\"" '((STRING . "Strinng+\"FOO\"")) )
(test-section "other")
(test-tlex "X++Y;" '((IDENTIFIER . X) PLUSPLUS (IDENTIFIER . Y) SEMICOLON))
(test-tlex "-12ul;" '(- (CONSTANT unsigned-long 12) SEMICOLON) )
(test-tlex "x**2;" '((IDENTIFIER . x) * * (CONSTANT int 2) SEMICOLON) )
;;Trigraphs are supposed to be processed in prior to lexer
;;(test-tlex "\"X??/\"" '())
;;Dollar sign canot be a part of identifier
;;(test-tlex "B$C;" '())
(test-tlex "A*=B;" '((IDENTIFIER . A) (ASSIGN . *=) (IDENTIFIER . B) SEMICOLON) )
;; ## operator is processed by cpp, lexer is not expected to see it.
;;(test-tlex "while##DO;" '())
;; If you don't want `gosh' to exit with nonzero status even if
;; the test fails, pass #f to :exit-on-failure.
(test-end :exit-on-failure #t)
;; EOF
| false |
9bb0f7d012e763c322db4fd13bd76f975fab6f59
|
fb93352482541f4269387c5872b9f1124a9182d3
|
/chenhao/chapter01/1.37.scm
|
39626217c4d57b6049578d33381afe5383d02f67
|
[] |
no_license
|
sicper/sicp-solutions
|
bfb5bd0f9f6eba0b396af88a4b5a2834ccfc5054
|
b79c3d9f193fbec26b5302f03de6dabd473203cf
|
refs/heads/master
| 2021-01-14T13:42:47.796733 | 2016-01-04T05:03:48 | 2016-01-04T05:03:48 | 38,525,815 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 404 |
scm
|
1.37.scm
|
(define (cont-frac-resursive D N i k)
(if (> i k)
0
(/ (N i) (+ (D i) (cont-frac-resursive D N (+ i 1) k)))
)
)
(define (cont-frac-iter D N k result)
(if (= 0 k)
result
(cont-frac-iter D N (- k 1) (/ (N k) (+ (D k) result)))
)
)
(newline)
(display (cont-frac-resursive (lambda (i) 1.0) (lambda (i) 1.0) 1.0 14))
(newline)
(display (cont-frac-iter (lambda (i) 1.0) (lambda (i) 1.0) 11 0.0))
| false |
82e3f9fab21155a71944438c5ad783d6dcbe178b
|
4bd59493b25febc53ac9e62c259383fba410ec0e
|
/Scripts/Task/ordered-words/scheme/ordered-words.ss
|
40d4d6997990b94bdab0abd58fd65c9e1377f3c2
|
[] |
no_license
|
stefanos1316/Rosetta-Code-Research
|
160a64ea4be0b5dcce79b961793acb60c3e9696b
|
de36e40041021ba47eabd84ecd1796cf01607514
|
refs/heads/master
| 2021-03-24T10:18:49.444120 | 2017-08-28T11:21:42 | 2017-08-28T11:21:42 | 88,520,573 | 5 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 694 |
ss
|
ordered-words.ss
|
(define sorted-words
(let ((port (open-input-file "unixdict.txt")))
(let loop ((char (read-char port)) (word '()) (result '(())))
(cond
((eof-object? char)
(reverse (map (lambda (word) (apply string word)) result)))
((eq? #\newline char)
(loop (read-char port) '()
(let ((best-length (length (car result))) (word-length (length word)))
(cond
((or (< word-length best-length) (not (apply char>=? word))) result)
((> word-length best-length) (list (reverse word)))
(else (cons (reverse word) result))))))
(else (loop (read-char port) (cons char word) result))))))
(map (lambda (x)
(begin
(display x)
(newline)))
sorted-words)
| false |
d4993bbff705359aececee68f962b7dd669681b0
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System/system/text/regular-expressions/capture-collection.sls
|
2b2e960640903268f83c6606ddc859add51c6ed4
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,540 |
sls
|
capture-collection.sls
|
(library (system text regular-expressions capture-collection)
(export is?
capture-collection?
get-enumerator
copy-to
count
is-read-only?
is-synchronized?
item
sync-root)
(import (ironscheme-clr-port))
(define (is? a)
(clr-is System.Text.RegularExpressions.CaptureCollection a))
(define (capture-collection? a)
(clr-is System.Text.RegularExpressions.CaptureCollection a))
(define-method-port
get-enumerator
System.Text.RegularExpressions.CaptureCollection
GetEnumerator
(System.Collections.IEnumerator))
(define-method-port
copy-to
System.Text.RegularExpressions.CaptureCollection
CopyTo
(System.Void System.Array System.Int32))
(define-field-port
count
#f
#f
(property:)
System.Text.RegularExpressions.CaptureCollection
Count
System.Int32)
(define-field-port
is-read-only?
#f
#f
(property:)
System.Text.RegularExpressions.CaptureCollection
IsReadOnly
System.Boolean)
(define-field-port
is-synchronized?
#f
#f
(property:)
System.Text.RegularExpressions.CaptureCollection
IsSynchronized
System.Boolean)
(define-field-port
item
#f
#f
(property:)
System.Text.RegularExpressions.CaptureCollection
Item
System.Text.RegularExpressions.Capture)
(define-field-port
sync-root
#f
#f
(property:)
System.Text.RegularExpressions.CaptureCollection
SyncRoot
System.Object))
| false |
e39815fa9e9dac557a98ebd542365b4a84a91ae0
|
309e1d67d6ad76d213811bf1c99b5f82fa2f4ee2
|
/A11b.ss
|
a553c9687dad3bc7ee2cba04b8b2c625bd98e033
|
[] |
no_license
|
lix4/CSSE304-Programming-Language-Concept-Code
|
d8c14c18a1baa61ab5d3df0b1ac650bdebc59526
|
dd94262865d880a357e85f6def697661e11c8e7a
|
refs/heads/master
| 2020-08-06T02:50:53.307301 | 2016-11-12T03:03:56 | 2016-11-12T03:03:56 | 73,528,000 | 1 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,012 |
ss
|
A11b.ss
|
;;Xiwen Li
;;Assignment 11b
(load "chez-init.ss"); This is a parser for simple Scheme expressions, such as those in EOPL, 3.1 thru 3.3.
; You will want to replace this with your parser that includes more expression types, more options for these types, and error-checking.
; Procedures to make the parser a little bit saner.
(define 1st car)
(define 2nd cadr)
(define 3rd caddr)
(define-datatype expression expression?
[var-exp (id symbol?)]
[lit-exp (id literals?)]
[lambda-exp (id symbol?)
(body expression?)]
[app-exp (rator expression?)
(rand expression?)]
[if-exp (test expression?)
(true expression?)
(false expression?)]
[if-no-else-exp (test expression?)
(true expression?)]
[let-exp (id list?)
(body (list-of expression?))]
[let*-exp (id list?)
(body (list-of expression?))]
[letrec-exp (id list?)
(body (list-of expression?))]
[set!-exp (var symbol?)
(val expression?)])
(define literals?
(lambda (obj)
(or (number? obj)
(symbol? obj)
(string? obj)
; (list? obj)
(boolean? obj))))
(define parse-exp
(lambda (datum)
(cond
[(symbol? datum) (var-exp datum)]
[(literals? datum) (lit-exp datum)]
[(pair? datum)
(cond [(eqv? (car datum) 'lambda)
(lambda-exp (car (2nd datum))
(parse-exp (3rd datum)))]
[(eqv? (1st datum) 'if)
(if (null? (cddr datum))
())]
[(eqv? (1st datum) 'let)
(let-exp (2nd datum)
(parse-exp (3rd datum)))]
[(eqv? (1st datum) 'let*)
(let*-exp (2nd datum)
(parse-exp (3rd datum)))]
[(eqv? (1st datum) 'letrec)
(letrec (2nd datum) (parse-exp (3nd datum)))]
[(eqv? (1st datum) 'set!)
(set!-exp (2nd datum) (parse-exp (3rd datum)))]
[else (app-exp (parse-exp (1st datum))
(parse-exp (2nd datum)))])]
[else (eopl:error 'parse-exp "bad expression: ~s" datum)])))
| false |
a33065ac48f86eb96b8e417ccd9ebeca597debc2
|
2a4d841aa312e1759f6cea6d66b4eaae81d67f99
|
/lisp/scheme/racket/unos/utils/os-utils.ss
|
0e8c84ce2b5bc4f922fc78242e418ef35fa0ed89
|
[] |
no_license
|
amit-k-s-pundir/computing-programming
|
9f8e136658322bb9a61e7160301c1a780cec84ca
|
9104f371fe97c9cd3c9f9bcd4a06038b936500a4
|
refs/heads/master
| 2021-07-12T22:46:09.849331 | 2017-10-16T08:50:48 | 2017-10-16T08:50:48 | 106,879,266 | 1 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,078 |
ss
|
os-utils.ss
|
(define-module (sonu os-utils)
#:use-module (ice-9 format))
(export ! !/sudo with-dir start-wireless)
(define-syntax-rule (with-dir dir body ...)
(let ((original-dir (getcwd)))
(chdir dir)
body ...
(chdir original-dir)))
(define-syntax !
(syntax-rules ()
((_ cmd args ...)
(let ((real-cmd-string (list 'cmd 'args ...)))
(system (string-join (map symbol->string real-cmd-string)))))))
(define (mount source dest . options)
(! mount source dest options))
(define-syntax !/sudo
(syntax-rules ()
((_ cmd args ...)
(system (string-append "echo sonu | sudo -S " (string-join (map
symbol->string
(list
'cmd
'args
...))))))))
(+ 2 5)
(define (start-wireless)
(!/sudo /home/sonu/start-wireless))
| true |
12b8c1f72e0919c3cc5820ce548baf1e00711757
|
a5e2d585f6b633a18238a52d98e543e7d11b2a9e
|
/17-sets.scm
|
232883bb5b6b672fa4b9944133e690da681edb34
|
[] |
no_license
|
tmtvl/sicp
|
435a9d529e60fdf3ac8bc1a4c13be9ce95a64cb4
|
86fea3ed61f5cfdad439ac18111acbb1bf20957d
|
refs/heads/master
| 2022-12-11T13:52:31.574222 | 2020-09-03T23:23:10 | 2020-09-03T23:23:10 | 289,768,375 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 14,618 |
scm
|
17-sets.scm
|
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1) (intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))
;; Exercise 2.59
(define (union-set set1 set2)
(define (U s)
(cond ((null? s) set2)
((element-of-set? (car s) set2)
(U (cdr s)))
(else (cons (car s) (U (cdr s))))))
(if (null? set2)
set1
(U set1)))
;; Exercise 2.60
(define (adjoin-set x set)
(cons x set))
(define (excise-from-set x set)
(define (E s)
(cond ((null? s) '())
((equal? (car s) x) (cdr s))
(else (cons (car s) (E (cdr s))))))
(E set))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1)
(excise-from-set (car set1) set2))))
(else (intersection-set (cdr set1) set2))))
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
(else (cons (car set1)
(union-set (cdr set1)
(excise-from-set (car set1) set2))))))
;; Sets as ordered lists
(define (element-of-set? x set)
(cond ((null? set) #f)
((= x (car set)) #t)
((< x (car set)) #f)
(else (element-of-set? x (cdr set)))))
(define (intersection-set set1 set2)
(if (or (null? set1) (null? set2))
'()
(let ((x1 (car set1))
(x2 (car set2)))
(cond ((= x1 x2)
(cons x1 (intersection-set (cdr set1)
(cdr set2))))
((< x1 x2)
(intersection-set (cdr set1) set2))
((< x2 x1)
(intersection-set set1 (cdr set2)))))))
;; Exercise 2.61
(define (adjoin-set x set)
(define (A s)
(cond ((null? s) (list x))
((= x (car s)) s)
((< x (car s)) (cons x s))
(else (cons (car s) (A (cdr s))))))
(A set))
;; Exercise 2.62
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
(else
(let ((x1 (car set1))
(x2 (car set2)))
(cond ((= x1 x2)
(cons x1 (union-set (cdr set1) (cdr set2))))
((< x1 x2)
(cons x1 (union-set (cdr set1) set2)))
(else
(cons x2 (union-set set1 (cdr set2)))))))))
;; Sets as binary trees
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
(define (element-of-set? x set)
(cond ((null? set) #f)
((= x (entry set)) #t)
((< x (entry set))
(element-of-set? x (left-branch set)))
((> x (entry set))
(element-of-set? x (right-branch set)))))
(define (adjoin-set x set)
(cond ((null? set) (make-tree x '() '()))
((= x (entry set)) set)
((< x (entry set))
(make-tree (entry set)
(adjoin-set x (left-branch set))
(right-branch set)))
((> x (entry set))
(make-tree (entry set)
(left-branch set)
(adjoin-set x (right-branch set))))))
;; Exercise 2.65
(define (intersection-set set1 set2)
(define (I s1 s2 sr)
(if (or (null? s1)
(null? s2))
sr
(let ((x1 (entry s1))
(x2 (entry s2)))
(cond
((= x1 x2)
(I (left-branch s1)
(left-branch s2)
(I (right-branch s1)
(right-branch s2)
(adjoin-set x1 sr))))
((< x1 x2)
(I s1
(left-branch s2)
(I (right-branch s1)
s2
sr)))
(else
(I s1
(right-branch s2)
(I (left-branch s1)
s2
sr)))))))
(I set1 set2 '()))
(define (union-set set1 set2)
(if (null? set1)
set2
(adjoin-set (entry set1)
(union-set
(left-branch set1)
(union-set (right-branch set1) set2)))))
;; Sets and intformation retrieval
(define (key record)
(car record))
(define (lookup given-key set-of-records)
(cond ((null? set-of-records) #f)
((equal? given-key (key (car set-of-records)))
(car set-of-records))
(else (lookup given-key (cdr set-of-records)))))
;; Exercise 2.66
(define (lookup given-key set-of-records)
(if (null? set-of-records)
#f
(let ((record (entry set-of-records)))
(cond ((= given-key (key record)) record)
((< given-key (key record))
(lookup given-key (left-branch set-of-records)))
(else
(lookup given-key (right-branch set-of-records)))))))
;; Huffman Encoding Trees
(define (make-leaf symbol weight)
(list 'leaf symbol weight))
(define (leaf? object)
(eq? (car object) 'leaf))
(define (symbol-leaf x)
(cadr x))
(define (weight-leaf x)
(caddr x))
(define (left-branch tree)
(car tree))
(define (right-branch tree)
(cadr tree))
(define (symbols tree)
(if (leaf? tree)
(list (symbol-leaf tree))
(caddr tree)))
(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)
(cadddr tree)))
(define (make-code-tree left right)
(list left
right
(append (symbols left) (symbols right))
(+ (weight left) (weight right))))
(define (choose-branch bit branch)
(cond ((= bit 0) (left-branch branch))
((= bit 1) (right-branch branch))
(else (error "bad bit: CHOOSE-BRANCH" bit))))
(define (decode bits tree)
(define (decode-1 bits current-branch)
(if (null? bits)
'()
(let ((next-branch
(choose-branch (car bits) current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-1 (cdr bits) tree))
(decode-1 (cdr bits) next-branch)))))
(decode-1 bits tree))
(define (adjoin-set x set)
(cond ((null? set) (list x))
((< (weight x) (weight (car set))) (cons x set))
(else (cons (car set)
(adjoin-set x (cdr set))))))
(define (make-leaf-set pairs)
(if (null? pairs)
'()
(let ((pair (car pairs)))
(adjoin-set (make-leaf (car pair)
(cadr pair))
(make-leaf-set (cdr pairs))))))
;; Exercise 2.67
(define sample-tree
(make-code-tree (make-leaf 'A 4)
(make-code-tree
(make-leaf 'B 2)
(make-code-tree
(make-leaf 'D 1)
(make-leaf 'C 1)))))
(define sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0))
(define sample-result (decode sample-message sample-tree))
;; Exercise 2.68
(define (encode-symbol symbol tree)
(define (E t p)
(cond ((null? t) #f)
((leaf? t)
(if (eq? (symbol-leaf t) symbol)
p
#f))
(else
(let ((lp (E (left-branch t)
(append p (list 0)))))
(if lp
lp
(E (right-branch t)
(append p (list 1))))))))
(let ((path (E tree '())))
(if path
path
(error "Symbol not in tree: ENCODE-SYMBOL" symbol tree))))
(define (encode message tree)
(if (null? message)
'()
(append (encode-symbol (car message) tree)
(encode (cdr message) tree))))
(equal? sample-message
(encode sample-result sample-tree))
;; Exercise 2.69
(define (successive-merge pairs)
(cond ((null? pairs) '())
((null? (cdr pairs)) (car pairs))
(else (successive-merge
(cons (make-code-tree (cadr pairs)
(car pairs))
(cddr pairs))))))
(define (generate-huffman-tree pairs)
(successive-merge (make-leaf-set pairs)))
(equal? sample-tree
(generate-huffman-tree '((A 4) (B 2) (D 1) (C 1))))
;; Exercise 2.70
(define rock-tree
(generate-huffman-tree
'((NA 16)
(YIP 9)
(SHA 3)
(A 2)
(GET 2)
(JOB 2)
(BOOM 1)
(WAH 1))))
(define rock-song
'(GET A JOB
SHA NA NA NA NA NA NA NA NA
GET A JOB
SHA NA NA NA NA NA NA NA NA
WAH YIP YIP YIP YIP YIP YIP YIP YIP YIP
SHA BOOM))
(define encoded-rock-song
(encode rock-song rock-tree))
;; Multiple representations for abstract data
(define (make-from-real-imag x y)
(cons x y))
(define (real-part z)
(car z))
(define (imag-part z)
(cdr z))
(define (add-complex z1 z2)
(make-from-real-imag (+ (real-part z1) (real-part z2))
(+ (imag-part z1) (imag-part z2))))
(define (sub-complex z1 z2)
(make-from-real-imag (- (real-part z1) (real-part z2))
(- (imag-part z1) (imag-part z2))))
(define (mul-complex z1 z2)
(make-from-mag-ang (* (magnitude z1) (magnitude z2))
(+ (angle z1) (angle z2))))
(define (div-complex z1 z2)
(make-from-mag-ang (/ (magnitude z1) (magnitude z2))
(- (angle z1) (angle z2))))
(define (square x)
(* x x))
(define (magnitude z)
(sqrt (+ (square (real-part z))
(square (imag-part z)))))
(define (angle z)
(atan (imag-part z) (real-part z)))
(define (make-from-mag-ang r a)
(cons (* r (cos a))
(* r (sin a))))
(define (real-part z)
(* (magnitude z)
(cos (angle z))))
(define (imag-part z)
(* (magnitude z)
(sin (angle z))))
(define (magnitude z)
(car z))
(define (angle z)
(cdr z))
(define (make-from-real-imag x y)
(cons (sqrt (+ (square x) (square y)))
(atan y x)))
(define (make-from-mag-ang r a)
(cons r a))
(define (attach-tag type-tag contents)
(cons type-tag contents))
(define (type-tag datum)
(if (pair? datum)
(car datum)
(error "Bad tagged datum: TYPE-TAG" datum)))
(define (contents datum)
(if (pair? datum)
(cdr datum)
(error "Bad tagged datum: CONTENTS" datum)))
(define (rectangular? z)
(eq? (type-tag z) 'rectangular))
(define (polar? z)
(eq? (type-tag z) 'polar))
(define (real-part-rectangular z)
(car z))
(define (imag-part-rectangular z)
(cdr z))
(define (magnitude-rectangular z)
(sqrt (+ (square (real-part-rectangular z))
(square (imag-part-rectangular z)))))
(define (angle-rectangular z)
(atan (imag-part-rectangular z)
(real-part-rectangular z)))
(define (make-from-real-imag-rectangular x y)
(attach-tag 'rectangular
(cons x y)))
(define (make-from-mag-ang-rectangular r a)
(attach-tag 'rectangular
(cons (* r (cos a))
(* r (sin a)))))
(define (real-part-polar z)
(* (magnitude-polar z)
(cos (angle-polar z))))
(define (imag-part-polar z)
(* (magnitude-polar z)
(sin (angle-polar z))))
(define (magnitude-polar z)
(car z))
(define (angle-polar z)
(cdr z))
(define (make-from-real-imag-polar x y)
(attach-tag 'polar
(cons (sqrt (+ (square x) (square y)))
(atan y x))))
(define (make-from-mag-ang-polar r a)
(attach-tag 'polar
(cons r a)))
(define (real-part z)
(cond ((rectangular? z)
(real-part-rectangular z))
((polar? z)
(real-part-polar z))
(else (error "Unknown type: REAL-PART" z))))
(define (imag-part z)
(cond ((rectangular? z)
(imag-part-rectangular z))
((polar? z)
(imag-part-polar z))
(else (error "Unknown type: IMAG-PART" z))))
(define (magnitude z)
(cond ((rectangular? z)
(magnitude-rectangular z))
((polar? z)
(magnitude-polar z))
(else (error "Unknown type: MAGNITUDE" z))))
(define (angle z)
(cond ((rectangular? z)
(angle-rectangular z))
((polar? z)
(angle-polar z))
(else (error "Unknown type: ANGLE" z))))
(define (make-from-real-imag x y)
(make-from-real-imag-rectangular x y))
(define (make-from-mag-ang r a)
(make-from-mag-ang-polar r a))
;; Exercise 2.73
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp) (if (same-variable? exp var) 1 0))
(else ((get 'deriv (operator exp))
(operands exp) var))))
(define (operator exp)
(car exp))
(define (operands exp)
(cdr exp))
(define (install-sum-package)
(define (deriv exp var)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
(define (addend s)
(cadr s))
(define (augend s)
(define (recur l)
(if (null? l)
'()
(make-sum (car l)
(recur (cdr l)))))
(recur (cddr s)))
(define (make-sum a1 a2)
(cond ((null? a2) a1)
((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1)
(number? a2))
(+ a1 a2))
((sum? a2)
(if (and (number? a1)
(number? (addend a2)))
(make-sum (+ a1 (addend a2))
(augend a2))
(append (list '+ a1)
(cdr a2))))
((number? a2)
(list '+ a2 a1))
(else (list '+ a1 a2))))
(define (sum? exp)
(and (pair? exp) (eq? (car exp) '+)))
(put 'deriv '(+) deriv)
(put 'addend '(+) addend)
(put 'augend '(+) augend)
(put 'make-sum'(+) make-sum)
(put 'sum? '(+) sum?))
(define (install-product-package)
(define (deriv exp var)
(make-product (deriv (multiplier exp) var)
(deriv (multiplicand exp) var)))
(define (multiplier s)
(cadr s))
(define (multiplicand s)
(define (recur l)
(if (null? l)
'()
(make-product (car l)
(recur (cdr l)))))
(recur (cddr s)))
(define (make-product m1 m2)
(cond ((null? m2) m1)
((or (=number? m1 0)
(=number? m2 0))
0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1)
(number? m2))
(* m1 m2))
((product? m2)
(if (and (number? m1)
(number? (multiplier m2)))
(make-product (* m1 (multiplier m2))
(multiplicand m2))
(append (list '* m1)
(cdr m2))))
((number? m2)
(list '* m2 m1))
(else (list '* m1 m2))))
(define (product? exp)
(and (pair? exp) (eq? (car exp) '*)))
(put 'deriv '(*) deriv)
(put 'multiplier '(*) multiplier)
(put 'multiplicand '(*) multiplicand)
(put 'make-product'(*) make-product)
(put 'product? '(*) product?))
(define (install-exponentiation-package)
(define (deriv exp var)
((get 'make-product '*)
(exponent exp)
((get 'make-product '*)
(make-exponentiation
(base exp)
((get 'make-sum '+)
(exponent exp) -1))
(deriv (base exp) var))))
(define (base s)
(cadr s))
(define (exponent s)
(caddr s))
(define (make-exponentiation b e)
(cond ((=number? e 0) 1)
((=number? b 1) b)
((and (number? b)
(number? e))
(expt b e))
(else (list '** b e))))
(define (exponentiation? exp)
(and (pair? exp) (eq? (car exp) '**)))
(put 'deriv '(**) deriv)
(put 'base'(**) multiplier)
(put 'exponent'(**) multiplicand)
(put 'make-exponentiation'(**) make-exponentiation)
(put 'exponentiation? '(**) exponentiation?))
;; Message passing
(define (make-from-real-imag x y)
(define (dispatch op)
(cond ((eq? op 'real-part) x)
((eq? op 'imag-part) y)
((eq? op 'magnitude) (sqrt (+ (square x)
(square y))))
((eq? op 'angle) (atan y x))
(else (error "Unknown op: MAKE-FROM-REAL-IMAG" op))))
dispatch)
(define (apply-generic op arg)
(arg op))
;; Exercise 2.75
(define (make-from-mag-ang r a)
(define (dispatch op)
(cond ((eq? op 'real-part) (* r (cos a)))
((eq? op 'imag-part) (* r (sin a)))
((eq? op 'magnitude) r)
((eq? op 'angle) a)
(else (error "Unknown op: MAKE-FROM-MAG-ANG" op))))
dispatch)
| false |
c2433ff27dfd096b1d210a5125df720f751dbd07
|
5f5bf90e51b59929b5e27a12657fade4a8b7f9cd
|
/src/player.scm
|
ed5cf52115629aa751f1cb1fc7f90c7e31bd8cf9
|
[] |
no_license
|
ashton314/NN_Chess
|
9ddd8ebc4a3594fcfe0b127ddd7309000eaa6594
|
f6c8295a622483641cdf883642723ee8e6e84e76
|
refs/heads/master
| 2020-04-25T04:16:00.493978 | 2014-01-01T22:24:01 | 2014-01-01T22:24:01 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,114 |
scm
|
player.scm
|
;;; Checkers player
;;; Ashton Wiersdorf
;;; Part of the NN_Chess project
(load-option 'format)
;(load "engine.scm")
;(declare (integrate-external "engine"))
(define (play-game depth)
(let ((board (make-board)))
; (board 'set-board! #(#(0 0 0 0) #(1 0 0 0) #(1 0 0 0) #(0 0 1 0) #(0 0 0 0) #(0 -1 -1 0) #(0 0 0 0) #(0 0 0 0)))
; (board 'set-board! #(#(0 0 0 0) #(0 0 0 0) #(0 0 0 0) #(1 1 1 1) #(0 0 0 0) #(-1 0 0 -1) #(0 0 0 0) #(0 0 0 0)))
(define (loop)
(board 'print)
(format #t "~%> ")
(let ((comm (read)))
(cond ((list? comm) (board 'move! comm) (loop))
((eq? comm 'go) (board 'move! (cadr (best-move-dumb (board 'dump-board) ((board 'turn) 'get) depth))) (loop))
((eq? comm 'quit) 'bye)
((eq? comm 'new-depth) (let ((num (prompt-for-expression (format #f "New depth (~A): " depth))))
(if (and (number? num) (integer? num) (positive? num)) (set! depth num))
(format #t "Depth is: ~A~%" depth)
(loop)))
((eq? comm 'term) (exit))
(else (format #t "I don't know that command.~%") (loop)))))
(loop)))
| false |
385367e73ce7df9e6931f5d6ec7d57e1f6ab70e0
|
c39b3eb88dbb1c159577149548d3d42a942fe344
|
/10-to-c/10-08-08-main.scm
|
4f16da73df3efc389743e05b97c44035f91a34b2
|
[] |
no_license
|
mbillingr/lisp-in-small-pieces
|
26694220205818a03efc4039e5a9e1ce7b67ff5c
|
dcb98bc847c803e65859e4a5c9801d752eb1f8fa
|
refs/heads/master
| 2022-06-17T20:46:30.461955 | 2022-06-08T17:50:46 | 2022-06-08T17:50:46 | 201,653,143 | 13 | 3 | null | 2022-06-08T17:50:47 | 2019-08-10T16:09:21 |
Scheme
|
UTF-8
|
Scheme
| false | false | 205 |
scm
|
10-08-08-main.scm
|
(define (generate-main out form)
(format out "~%/* Expression: */~%void main(void) {~%")
(format out " SCM_print")
(between-parentheses out
(->C form out))
(format out ";~% exit(0);~%}~%"))
| false |
fc226a67ae0ff8bad6e9ce427015299d353796ac
|
2fc7c18108fb060ad1f8d31f710bcfdd3abc27dc
|
/lib/fluid-let-sr.scm
|
712d26b10045d0bbef63838070827104582501c5
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0"
] |
permissive
|
bakul/s9fes
|
97a529363f9a1614a85937a5ef9ed6685556507d
|
1d258c18dedaeb06ce33be24366932143002c89f
|
refs/heads/master
| 2023-01-24T09:40:47.434051 | 2022-10-08T02:11:12 | 2022-10-08T02:11:12 | 154,886,651 | 68 | 10 |
NOASSERTION
| 2023-01-25T17:32:54 | 2018-10-26T19:49:40 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,198 |
scm
|
fluid-let-sr.scm
|
; Scheme 9 from Empty Space, Function Library
; By Nils M Holm, 2009
; Placed in the Public Domain
;
; (fluid-let ((variable expression) ...) expression ...) ==> object
;
; Bind variables dynamically, i.e. assign a dynamic (rather than
; a lexical/static) value to each given variable. The variables
; must be defined outside of FLUID-LET. The difference between
; LET and FLUID-LET is as follows:
;
; (let ((a 0)) (let ((a 0))
; (let ((f (lambda () a))) (let ((f (lambda () a)))
; (let ((a 1)) (fluid-let ((a 1))
; (f)))) ==> 0 (f)))) ==> 1
;
; Example: (let ((a 0))
; (let ((f (lambda () a)))
; (fluid-let ((a 1))
; (f)))) ==> 1
; This implementation is inefficient, use "fluid-let.scm" instead.
(load-from-library "syntax-rules.scm")
(define-syntax fluid-let
(syntax-rules ()
((_ () expr . exprs)
(begin expr . exprs))
((_ ((v1 a1) (v2 a2) ...) expr . exprs)
(let ((outer-v v1))
(set! v1 a1)
(fluid-let ((v2 a2) ...)
(let ((r (begin expr . exprs)))
(set! v1 outer-v)
r))))))
| true |
c702284d372acf99081195002be14a8c5beef052
|
de8566db6f92103165b07a24ceacf8b20a7ac542
|
/sharelock/data/filter02.scm
|
f9245af68c89dcc833619ae1f862228e885f5c36
|
[] |
no_license
|
Irwin1985/cerbo
|
a786ab8af9e4b2f139898bd1ddf557fb6d89b5dd
|
559df220dc842318c4c2d81100b56bf6587c91a6
|
refs/heads/master
| 2022-09-01T15:46:17.400733 | 2020-05-27T19:21:37 | 2020-05-27T19:21:37 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 339 |
scm
|
filter02.scm
|
;;;; (load "filter02.scm")
;;(use srfi-1)
;;(require-library format)
;;(import (prefix format fmt:))
(load "~/repos/nokilli/sharelock/sharelock.scm")
(write-line "Filter: Monotonically increasing dividends, ROE0 >15")
(filter-and-tabulate
(lambda (v) (and (= 1 (v 'DIVR))
(> (v 'ROE0) 15)))
'(EPIC PER0 ROE0 RREV))
| false |
b51576db6bf16f185e1e51ab81d99cadb6ebff3a
|
958488bc7f3c2044206e0358e56d7690b6ae696c
|
/poly/DesignPatterns/Builder/builder.scm
|
c36dc34c4476a0ccb7b392e479019d25819092ff
|
[] |
no_license
|
possientis/Prog
|
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
|
d4b3debc37610a88e0dac3ac5914903604fd1d1f
|
refs/heads/master
| 2023-08-17T09:15:17.723600 | 2023-08-11T12:32:59 | 2023-08-11T12:32:59 | 40,361,602 | 3 | 0 | null | 2023-03-27T05:53:58 | 2015-08-07T13:24:19 |
Coq
|
UTF-8
|
Scheme
| false | false | 12,355 |
scm
|
builder.scm
|
; Builder Design Pattern
; The main idea behind the builder design pattern is
; to provide an abstract interface for a 'builder object'
; A concrete builder object is not a factory object which returns
; a ready-made object of a certain type. A concrete builder object
; should be viewed as a toolbox allowing someone else (that someone
; else is called 'a director' within the context of the builer design
; pattern) to build an object of some type according to some plan.
; Let us define a possible 'director' class, whose purpose
; it is to manufacture meals
(define DirectorCook
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'makeMeal)(makeMeal data))
(else (display "DirectorCook: unknown operation error\n")))))
; This is the main method of the director, which creates an object
; based on some logic and algorithm which is encapsulated in the
; method body, and uses the tools provided by the builder interface.
(define (makeMeal data)
((data 'builder) 'startNewMeal)
((data 'builder) 'addBurger)
((data 'builder) 'addDrink))
;
(lambda args
(define _builder (car args))
(define (data m)
(cond ((eq? m 'builder) _builder)
(else (display "DirectorCook: should not happen\n"))))
(this data))))
; Note that the manufacture algorithm contained in the director
; is very general and does not tell us anything about the type of
; the object being created, let alone its internal representation.
(define MealBuilder
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'startNewMeal) (startNewMeal data))
((eq? m 'addBurger) (addBurger data))
((eq? m 'addDrink) (addDrink data))
(else (display "MealBuilder: unknown operation error\n")))))
;
(define (startNewMeal data)
(display "MealBuilder::startNewMeal is not implemented\n"))
(define (addBurger data)
(display "MealBuilder::addBurger is not implemented\n"))
(define (addDrink data)
(display "MealBuilder::addDrink is not implemented\n"))
;
(lambda args
(this #f)))) ; args ignored
; We can implement MealBuilder in many different ways, so as to
; construct objects of many possible types which do not even need
; to be related by a common base class 'Meal'
; However, at some point we need to retrieve the constructed object
; so there must be some method 'getObject'. In general, because the
; return type of 'getObject' may be arbitrary, the method declaration
; cannot be part of the interface MealBuilder as this would constrain
; the implementation to a specific type being constructed.
; In this example, we shall consider two concrete implementations of
; MealBuilder, a 'VegetarianMealBuilder' and a 'NonVegetarianMealBuilder'.
; Both implementation will allow the construction of objects of the same
; type, but one should remember that this need not be the case when
; applying the builder design pattern.
; Concrete implementations of MealBuilder will hold an object of type
; Meal (the object being constructed), and will have a getObject() method.
(define VegetarianMealBuilder
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'startNewMeal)(startNewMeal data))
((eq? m 'addBurger)(addBurger data))
((eq? m 'addDrink)(addDrink data))
((eq? m 'getMeal)(getMeal data))
(else ((data 'base) m))))) ; not useful, just practicing
;
(define (startNewMeal data)
(data 'new))
;
(define (addBurger data)
(((data 'meal) 'addItem) (VegBurger)))
;
(define (addDrink data)
(((data 'meal) 'addItem) (Coke)))
;
(define (getMeal data)
(data 'meal))
;
(lambda args ; args ignored
(define _meal #f)
(define _base (MealBuilder)) ; not really useful, just practicing
(define (data m)
(cond ((eq? m 'new)(set! _meal (Meal)))
((eq? m 'meal) _meal)
((eq? m 'base) _base)
(else (display "VegetarianMealBuilder: should not happen\n"))))
(this data))))
(define NonVegetarianMealBuilder
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'startNewMeal)(startNewMeal data))
((eq? m 'addBurger)(addBurger data))
((eq? m 'addDrink)(addDrink data))
((eq? m 'getMeal)(getMeal data))
(else ((data 'base) m))))) ; not useful, just practicing
;
(define (startNewMeal data)
(data 'new))
;
(define (addBurger data)
(((data 'meal) 'addItem) (ChickenBurger)))
;
(define (addDrink data)
(((data 'meal) 'addItem) (Pepsi)))
;
(define (getMeal data)
(data 'meal))
;
(lambda args ; args ignored
(define _meal #f)
(define _base (MealBuilder)) ; not really useful, just practicing
(define (data m)
(cond ((eq? m 'new)(set! _meal (Meal)))
((eq? m 'meal) _meal)
((eq? m 'base) _base)
(else (display "NonVegetarianMealBuilder: should not happen\n"))))
(this data))))
; Both of the above concrete builders happen to produce objects
; of the same type 'Meal' implemented as a list of 'Item'
(define Meal
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'addItem)(addItem data))
((eq? m 'getCost)(getCost data))
((eq? m 'showItems)(showItems data))
(else (display "Meal:unknown operation error\n")))))
;
(define (addItem data)
(data 'add!))
;
(define (getCost data)
(let loop ((cost 0) (items (data 'items)))
(if (null? items)
cost
(loop (+ cost ((car items) 'price)) (cdr items)))))
;
(define (showItems data)
(let loop ((items (data 'items)))
(if (null? items)
'done
(begin
(let ((that (car items))) ; Scheme case insensitive, need 'that'
(display "Item : ")
(display (that 'name))
(display ", Packing : ")
(display ((that 'packing) 'pack))
(display ", Price : ")
(display (that 'price))
(newline))
(loop (cdr items))))))
;
(lambda args ;args ignored
(define _items '())
(define (data m)
(cond ((eq? m 'items) _items)
((eq? m 'add!) (lambda (x) (set! _items (cons x _items))))
(else (display "Meal: should not happen\n"))))
(this data))))
(define Item
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'price)) (price data)
((eq? m 'name) (name data))
((eq? m 'packing) (_packing data))
(else (display "Item: unknown operation error\n")))))
;
(define (price data)
(display "Item::price is not implemented\n"))
;
(define (name data)
(display "Item::name is not implemented\n"))
;
(define (_packing data) ; Scheme case insensitive, hence '_packing'
(display "Item::packing is not implemented\n"))
;
(lambda args
(this #f))))
(define Packing
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'pack)(pack data))
(else (display "Packing: unknown operation error\n")))))
;
(define (pack data)
(display "Packing::pack is not implemented\n"))
;
(lambda args
(this #f))))
(define Wrapper
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'pack)(pack data))
(else ((data 'base) m)))))
;
(define (pack data)
"Wrapper")
;
(lambda args
(define _base (Packing)) ; not useful
(define (data m)
(cond ((eq? m 'base) _base)
(else (display "Wrapper: should not happen\n"))))
(this data))))
(define Bottle
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'pack)(pack data))
(else ((data 'base) m)))))
;
(define (pack data)
"Bottle")
;
(lambda args
(define _base (Packing)) ; not useful
(define (data m)
(cond ((eq? m 'base) _base)
(else (display "Bottle: should not happen\n"))))
(this data))))
(define Burger
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'packing) (_packing data))
(else ((data 'base) m)))))
;
(define (_packing data)
(Wrapper))
;
(lambda args
(define _base (Item))
(define (data m)
(cond ((eq? m 'base) _base)
(else (display "Burger: should not happen\n"))))
(this data))))
(define ColdDrink
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'packing) (_packing data))
(else ((data 'base) m)))))
;
(define (_packing data)
(Bottle))
;
(lambda args
(define _base (Item))
(define (data m)
(cond ((eq? m 'base) _base)
(else (display "ColdDrink: should not happen\n"))))
(this data))))
(define VegBurger
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'price) 2.5)
((eq? m 'name) "Veg Burger")
(else ((data 'base) m)))))
;
(lambda args
(define _base (Burger))
(define (data m)
(cond ((eq? m 'base) _base)
(else (display "VegBurger: should not happen\n"))))
(this data))))
(define ChickenBurger
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'price) 5.05)
((eq? m 'name) "Chicken Burger")
(else ((data 'base) m)))))
;
(lambda args
(define _base (Burger))
(define (data m)
(cond ((eq? m 'base) _base)
(else (display "ChickenBurger: should not happen\n"))))
(this data))))
(define Coke
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'price) 3.0)
((eq? m 'name) "Coke")
(else ((data 'base) m)))))
;
(lambda args
(define _base (ColdDrink))
(define (data m)
(cond ((eq? m 'base) _base)
(else (display "Coke: should not happen\n"))))
(this data))))
(define Pepsi
(let ((namespace #f)) ; just name hiding
; public interface
(define (this data)
(lambda (m)
(cond ((eq? m 'price) 3.5)
((eq? m 'name) "Pepsi")
(else ((data 'base) m)))))
;
(lambda args
(define _base (ColdDrink))
(define (data m)
(cond ((eq? m 'base) _base)
(else (display "Pepsi: should not happen\n"))))
(this data))))
; creating vegetarian meal
; First we create the appropriate concrete builder
(define vegBuilder (VegetarianMealBuilder))
; Next we create a director which will use this builder
(define cook (DirectorCook vegBuilder))
; Next we let the cook prepare the meal
(cook 'makeMeal)
; Next we retrieve the object from the builder
(define vegMeal (vegBuilder 'getMeal))
; outputting result
(display "Veg Meal\n")
(vegMeal 'showItems)
(display "Total Cost: ")
(display (vegMeal 'getCost))
(newline)
;
; same for non-vegetarian meal
(define nonVegBuilder (NonVegetarianMealBuilder))
(define cook (DirectorCook nonVegBuilder))
(cook 'makeMeal)
(define nonVegMeal (nonVegBuilder 'getMeal))
; outputting result
(display "\nNon-Veg Meal\n")
(nonVegMeal 'showItems)
(display "Total Cost: ")
(display (nonVegMeal 'getCost))
(newline)
(exit 0)
| false |
b9b964577cfd31e43ac556cd3d7b49ed11c9e971
|
b58f908118cbb7f5ce309e2e28d666118370322d
|
/src/32.scm
|
8a0fb8e882e85be533ee985153db7f03bfeb61f7
|
[
"MIT"
] |
permissive
|
arucil/L99
|
a9e1b7ad2634850db357f7cc292fa2871997d93d
|
8b9a3a8e7fb63efb2d13fab62cab2c1254a066d9
|
refs/heads/master
| 2021-09-01T08:18:39.029308 | 2017-12-26T00:37:55 | 2017-12-26T00:37:55 | 114,847,976 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 216 |
scm
|
32.scm
|
(load "prelude.scm")
;;; P32
(define (gcd a b)
(cond
[(zero? a) b]
[(zero? b) a]
[else
(gcd b (remainder a b))]))
(test (gcd 10 15) 5)
(test (gcd 15 10) 5)
(test (gcd 11 13) 1)
(test (gcd 36 63) 9)
| false |
d7903ed4ee0e8746683b46d49871a1453db3e81a
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/test/tests/rsa/pkcs/%3a10.scm
|
ae4e6520df1342f03b704416aba973f6ba36df19
|
[
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"BSD-2-Clause"
] |
permissive
|
ktakashi/sagittarius-scheme
|
0a6d23a9004e8775792ebe27a395366457daba81
|
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
|
refs/heads/master
| 2023-09-01T23:45:52.702741 | 2023-08-31T10:36:08 | 2023-08-31T10:36:08 | 41,153,733 | 48 | 7 |
NOASSERTION
| 2022-07-13T18:04:42 | 2015-08-21T12:07:54 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,649 |
scm
|
%3a10.scm
|
(import (rnrs)
(crypto)
(rsa pkcs :10)
(clos user)
(rfc pem)
(asn.1)
(srfi :64))
(test-begin "PKCS 10")
(let ()
(define key-pem
"-----BEGIN PUBLIC KEY-----
MIIBHzANBgkqhkiG9w0BAQEFAAOCAQwAMIIBBwKBgQMwO3kPsUnaNAbUlaubn7ip
4pNEXjvUOxjvLwUhtybr6Ng4undLtSQPCPf7ygoUKh1KYeqXMpTmhKjRos3xioTy
23CZuOl3WIsLiRKSVYyqBc9d8rxjNMXuUIOiNO38ealcR4p44zfHI66INPuKmTG3
RQP/6p5hv1PYcWmErEeDewKBgGEXxgRIsTlFGrW2C2JXoSvakMCWD60eAH0W2PpD
qlqqOFD8JA5UFK0roQkOjhLWSVu8c6DLpWJQQlXHPqP702qIg/gx2o0bm4EzrCEJ
4gYo6Ax+U7q6TOWhQpiBHnC0ojE8kUoqMhfALpUaruTJ6zmj8IA1e1M6bMqVF8sr
lb/N
-----END PUBLIC KEY-----")
(let-values (((param content) (parse-pem-string key-pem)))
(let* ((spki (import-public-key PKCS10 content))
(bv (asn.1-encode (asn.1-encodable->asn.1-object spki))))
(test-assert (subject-public-key-info? spki))
(test-assert (public-key? (subject-public-key-info->public-key spki)))
(test-assert (is-a? (subject-public-key-info->public-key spki)
<rsa-public-key>))
(test-equal bv (export-public-key spki)))))
(let ()
(define key-pem
"-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE=
-----END PUBLIC KEY-----")
(let-values (((param content) (parse-pem-string key-pem)))
(let* ((spki (import-public-key PKCS10 content))
(bv (asn.1-encode (asn.1-encodable->asn.1-object spki))))
(test-assert (subject-public-key-info? spki))
(test-assert (public-key? (subject-public-key-info->public-key spki)))
(test-assert (is-a? (subject-public-key-info->public-key spki)
<eddsa-public-key>))
(test-equal bv (export-public-key spki)))))
(test-end)
| false |
ece92e72098e835e16ba2bbd55ca29bd8b623671
|
7f3f185931818a0be4e256040704e2830d253b18
|
/pip-tui/event.scm
|
e524c866d2eaa41c5e611fde2c6fba37349e93da
|
[] |
no_license
|
spk121/pip-tui
|
f405f240a5091ecab2f01ef145a1b3f5d38b65e3
|
7fafdadf80f5dcf867639af9fefa87fe1443fd78
|
refs/heads/master
| 2021-01-20T18:28:35.615714 | 2016-07-29T15:43:49 | 2016-07-29T15:43:49 | 60,352,270 | 7 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,260 |
scm
|
event.scm
|
(define-module (pip-tui event)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (ncurses curses)
#:use-module (pip-tui typecheck)
#:export (event-get-data
assert-event
kbd-event-new
kbd-event?
mouse-event-new
mouse-event?
signal-event-new
signal-event?
resize-event-new
resize-event?
symbolic-event-new
symbolic-event?
idle-event-new
idle-event?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; EVENT
;; An event is a simple class that represents some action
;; that occurs in the main loop.
;; The event types are
;; 1. keyboard events
;; 2. mouse events
;; 3. POSIX signals (unimplemented)
;; 4. terminal resize events, SIGWINCH (unimplemented)
;; 5. symbolic -- a scheme symbol pushed onto the main loop
;; 6. idle -- a timestamp event fired automatically when idle
;; These are fired by the main loop
(define-record-type <event>
(event-new type
data)
event?
(type event-get-type event-set-type!)
(data event-get-data event-set-data!))
(define-syntax assert-event
(syntax-rules ()
((_ val)
(typecheck val 'event event?))))
(define-syntax assert-mevent
(syntax-rules ()
((_ val)
(typecheck val 'mevent mevent?))))
(define (kbd-event-new key-or-char)
;; FIXME assert integer or char
(event-new 'kbd key-or-char))
(define (kbd-event? x)
(assert-event x)
(eq? (event-get-type x) 'kbd))
(define (mouse-event-new mevent)
(assert-mevent mevent)
(event-new 'mouse mevent))
(define (mouse-event? x)
(assert-event x)
(eq? (event-get-type x) 'mouse))
(define (signal-event-new posix-signal-id)
(event-new 'signal posix-signal-id))
(define (signal-event? x)
(assert-event x)
(eq? (event-get-type x) 'signal))
(define (resize-event-new x)
(event-new 'resize x))
(define (resize-event? x)
(assert-event x)
(eq? (event-get-type x) 'resize))
(define (symbolic-event-new sym data)
(event-new 'symbolic (cons sym data)))
(define (symbolic-event? x)
(assert-event x)
(eq? (event-get-type x) 'symbolic))
(define (idle-event-new time-cur delta-time)
(event-new 'idle (cons time-cur delta-time)))
(define (idle-event? x)
(assert-event x)
(eq? (event-get-type x) 'idle))
| true |
c0897098429e5302e02b86afc731841d1488564a
|
486987d683c996171c3d52f4466574f60ad451be
|
/srfi-excerpts.scm
|
0ab62f57924699be266fa9c9c75c3ef9f14efb90
|
[] |
no_license
|
drcz/cowgirl-or-invader
|
5ea3a35ee7631b642830eccda686ebe0257f4fa3
|
d56944ed80b527675166377edc03952488173f53
|
refs/heads/master
| 2016-08-11T09:52:18.737877 | 2016-01-15T16:33:36 | 2016-01-15T16:33:36 | 49,728,137 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 13,861 |
scm
|
srfi-excerpts.scm
|
(define-syntax let-string-start+end
(syntax-rules ()
((let-string-start+end (start end) proc s-exp args-exp body ...)
(receive (start end) (string-parse-final-start+end proc s-exp args-exp)
body ...))
((let-string-start+end (start end rest) proc s-exp args-exp body ...)
(receive (rest start end) (string-parse-start+end proc s-exp args-exp)
body ...))))
;;; This one parses out a *pair* of final start/end indices.
;;; Not exported; for internal use.
(define-syntax let-string-start+end2
(syntax-rules ()
((l-s-s+e2 (start1 end1 start2 end2) proc s1 s2 args body ...)
(let ((procv proc)) ; Make sure PROC is only evaluated once.
(let-string-start+end (start1 end1 rest) procv s1 args
(let-string-start+end (start2 end2) procv s2 rest
body ...))))))
(define-syntax receive
(syntax-rules ()
((_ args expr body ...)
(call-with-values (lambda () expr) (lambda args body ...)))))
(define (string-contains super sub)
(let ((l1 (string-length super))
(l2 (string-length sub)))
(let loop ((i 0))
(cond ((> (+ i l2) l1)
#f)
((string=? (substring super i (+ i l2)) sub)
i)
(else
(loop (+ i 1)))))))
(define (string-contains-ci super sub)
(let ((l1 (string-length super))
(l2 (string-length sub)))
(let loop ((i 0))
(cond ((> (+ i l2) l1)
#f)
((string-ci=? (substring super i (+ i l2)) sub)
i)
(else
(loop (+ i 1)))))))
(define (string-prefix? s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-prefix? s1 s2 maybe-starts+ends
(%string-prefix? s1 start1 end1 s2 start2 end2)))
(define (string-suffix? s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-suffix? s1 s2 maybe-starts+ends
(%string-suffix? s1 start1 end1 s2 start2 end2)))
(define (%string-prefix? s1 start1 end1 s2 start2 end2)
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2)) ; Quick check
(= (%string-prefix-length s1 start1 end1
s2 start2 end2)
len1))))
(define (%string-suffix? s1 start1 end1 s2 start2 end2)
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2)) ; Quick check
(= len1 (%string-suffix-length s1 start1 end1
s2 start2 end2)))))
(define (%string-prefix-length s1 start1 end1 s2 start2 end2)
(let* ((delta (min (- end1 start1) (- end2 start2)))
(end1 (+ start1 delta)))
(if (and (eq? s1 s2) (= start1 start2)) ; EQ fast path
delta
(let lp ((i start1) (j start2)) ; Regular path
(if (or (>= i end1)
(not (char=? (string-ref s1 i)
(string-ref s2 j))))
(- i start1)
(lp (+ i 1) (+ j 1)))))))
(define (%string-suffix-length s1 start1 end1 s2 start2 end2)
(let* ((delta (min (- end1 start1) (- end2 start2)))
(start1 (- end1 delta)))
(if (and (eq? s1 s2) (= end1 end2)) ; EQ fast path
delta
(let lp ((i (- end1 1)) (j (- end2 1))) ; Regular path
(if (or (< i start1)
(not (char=? (string-ref s1 i)
(string-ref s2 j))))
(- (- end1 i) 1)
(lp (- i 1) (- j 1)))))))
(define (string-parse-final-start+end proc s args)
(receive (rest start end) (string-parse-start+end proc s args)
(if (pair? rest) (error "Extra arguments to procedure" proc rest)
(values start end))))
(define (string-parse-start+end proc s args)
(if (not (string? s)) (error "Non-string value" proc s))
(let ((slen (string-length s)))
(if (pair? args)
(let ((start (car args))
(args (cdr args)))
(if (and (integer? start) (exact? start) (>= start 0))
(receive (end args)
(if (pair? args)
(let ((end (car args))
(args (cdr args)))
(if (and (integer? end) (exact? end) (<= end slen))
(values end args)
(error "Illegal substring END spec" proc end s)))
(values slen args))
(if (<= start end) (values args start end)
(error "Illegal substring START/END spec"
proc start end s)))
(error "Illegal substring START spec" proc start s)))
(values '() 0 slen))))
(define (%string-copy! to tstart from fstart fend)
(if (> fstart tstart)
(do ((i fstart (+ i 1))
(j tstart (+ j 1)))
((>= i fend))
(string-set! to j (string-ref from i)))
(do ((i (- fend 1) (- i 1))
(j (+ -1 tstart (- fend fstart)) (- j 1)))
((< i fstart))
(string-set! to j (string-ref from i)))))
(define (string-concatenate strings)
(let* ((total (do ((strings strings (cdr strings))
(i 0 (+ i (string-length (car strings)))))
((not (pair? strings)) i)))
(ans (make-string total)))
(let lp ((i 0) (strings strings))
(if (pair? strings)
(let* ((s (car strings))
(slen (string-length s)))
(%string-copy! ans i s 0 slen)
(lp (+ i slen) (cdr strings)))))
ans))
(define (string-join strings delim)
(if (null? strings)
""
(let ((buildit (lambda (lis final)
(let recur ((lis lis))
(if (pair? lis)
(cons delim (cons (car lis) (recur (cdr lis))))
final)))))
(string-concatenate (cons (car strings) (buildit (cdr strings) '()))))))
(define (white-char? ch)
(or (char=? ch #\space)
(char=? ch #\newline)
(char=? ch #\linefeed)
(char=? ch #\return)
(char=? ch #\tab)))
(define (string-trim-both str)
(let* ((pos (let loop ((pos 0))
(if (and (< pos (string-length str))
(white-char? (string-ref str pos)))
(loop (+ 1 pos))
pos)))
(str1 (substring str pos (string-length str)))
(pos (let loop ((pos (- (string-length str1) 1)))
(if (and (>= pos 0)
(white-char? (string-ref str1 pos)))
(loop (- pos 1))
pos)))
(str2 (substring str1 0 (+ pos 1))))
str2))
(define (car+cdr pair) (values (car pair) (cdr pair)))
(define first car)
(define (null-list? l)
(cond ((pair? l) #f)
((null? l) #t)
(else (error "null-list?: argument out of domain" l))))
(define (%cars+cdrs lists)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(receive (list other-lists) (car+cdr lists)
(if (null-list? list) (abort '() '()) ; LIST is empty -- bail out
(receive (a d) (car+cdr list)
(receive (cars cdrs) (recur other-lists)
(values (cons a cars) (cons d cdrs))))))
(values '() '()))))))
(define (%cars+cdrs+ lists cars-final)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(receive (list other-lists) (car+cdr lists)
(if (null-list? list) (abort '() '()) ; LIST is empty -- bail out
(receive (a d) (car+cdr list)
(receive (cars cdrs) (recur other-lists)
(values (cons a cars) (cons d cdrs))))))
(values (list cars-final) '()))))))
(define (%cdrs lists)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(let ((lis (car lists)))
(if (null-list? lis) (abort '())
(cons (cdr lis) (recur (cdr lists)))))
'())))))
(define (%cars+ lists last-elt) ; (append! (map car lists) (list last-elt))
(let recur ((lists lists))
(if (pair? lists) (cons (caar lists) (recur (cdr lists))) (list last-elt))))
(define (every pred lis1 . lists)
(if (pair? lists)
;; N-ary case
(receive (heads tails) (%cars+cdrs (cons lis1 lists))
(or (not (pair? heads))
(let lp ((heads heads) (tails tails))
(receive (next-heads next-tails) (%cars+cdrs tails)
(if (pair? next-heads)
(and (apply pred heads) (lp next-heads next-tails))
(apply pred heads)))))) ; Last PRED app is tail call.
;; Fast path
(or (null-list? lis1)
(let lp ((head (car lis1)) (tail (cdr lis1)))
(if (null-list? tail)
(pred head) ; Last PRED app is tail call.
(and (pred head) (lp (car tail) (cdr tail))))))))
(define (any pred lis1 . lists)
(if (pair? lists)
;; N-ary case
(receive (heads tails) (%cars+cdrs (cons lis1 lists))
(and (pair? heads)
(let lp ((heads heads) (tails tails))
(receive (next-heads next-tails) (%cars+cdrs tails)
(if (pair? next-heads)
(or (apply pred heads) (lp next-heads next-tails))
(apply pred heads)))))) ; Last PRED app is tail call.
;; Fast path
(and (not (null-list? lis1))
(let lp ((head (car lis1)) (tail (cdr lis1)))
(if (null-list? tail)
(pred head) ; Last PRED app is tail call.
(or (pred head) (lp (car tail) (cdr tail))))))))
(define (filter pred lis) ; Sleazing with EQ? makes this one faster
(let recur ((lis lis))
(if (null-list? lis) lis ; Use NOT-PAIR? to handle dotted lists.
(let ((head (car lis))
(tail (cdr lis)))
(if (pred head)
(let ((new-tail (recur tail))) ; Replicate the RECUR call so
(if (eq? tail new-tail) lis
(cons head new-tail)))
(recur tail)))))) ; this one can be a tail call.
(define (fold kons knil lis1 . lists)
(if (pair? lists)
(let lp ((lists (cons lis1 lists)) (ans knil)) ; N-ary case
(receive (cars+ans cdrs) (%cars+cdrs+ lists ans)
(if (null? cars+ans) ans ; Done.
(lp cdrs (apply kons cars+ans)))))
(let lp ((lis lis1) (ans knil)) ; Fast path
(if (null-list? lis) ans
(lp (cdr lis) (kons (car lis) ans))))))
(define (reduce f ridentity lis)
(if (null-list? lis) ridentity
(fold f (car lis) (cdr lis))))
(define (fold-right kons knil lis1 . lists)
(if (pair? lists)
(let recur ((lists (cons lis1 lists))) ; N-ary case
(let ((cdrs (%cdrs lists)))
(if (null? cdrs) knil
(apply kons (%cars+ lists (recur cdrs))))))
(let recur ((lis lis1)) ; Fast path
(if (null-list? lis) knil
(let ((head (car lis)))
(kons head (recur (cdr lis))))))))
(define (delete x lis =)
(filter (lambda (y) (not (= x y))) lis))
(define (delete-duplicates lis =)
(let recur ((lis lis))
(if (null-list? lis) lis
(let* ((x (car lis))
(tail (cdr lis))
(new-tail (recur (delete x tail =))))
(if (eq? tail new-tail) lis (cons x new-tail))))))
(define (list-index pred lis1 . lists)
(if (pair? lists)
;; N-ary case
(let lp ((lists (cons lis1 lists)) (n 0))
(receive (heads tails) (%cars+cdrs lists)
(and (pair? heads)
(if (apply pred heads) n
(lp tails (+ n 1))))))
;; Fast path
(let lp ((lis lis1) (n 0))
(and (not (null-list? lis))
(if (pred (car lis)) n (lp (cdr lis) (+ n 1)))))))
(define (drop lis k)
(let iter ((lis lis) (k k))
(if (zero? k) lis (iter (cdr lis) (- k 1)))))
(define (lset-uni-2 a b)
(cond ((null? a) b)
((member (car a) b) (lset-uni-2 (cdr a) b))
(else (cons (car a) (lset-uni-2 (cdr a) b)))))
(define (lset-union = . lists)
(reduce (lambda (lis ans) ; Compute ANS + LIS.
(cond ((null? lis) ans) ; Don't copy any lists
((null? ans) lis) ; if we don't have to.
((eq? lis ans) ans)
(else
(fold (lambda (elt ans) (if (any (lambda (x) (= x elt)) ans)
ans
(cons elt ans)))
ans lis))))
'() lists))
(define (find-tail pred list)
(let lp ((list list))
(and (not (null-list? list))
(if (pred (car list)) list
(lp (cdr list))))))
(define (member= x lis =)
(find-tail (lambda (y) (= x y)) lis))
(define (lset-difference = lis1 . lists)
(let ((lists (filter pair? lists))) ; Throw out empty lists.
(cond ((null? lists) lis1) ; Short cut
((memq lis1 lists) '()) ; Short cut
(else (filter (lambda (x)
(every (lambda (lis) (not (member= x lis =)))
lists))
lis1)))))
(define (%lset2<= = lis1 lis2) (every (lambda (x) (member= x lis2 =)) lis1))
(define (lset<= = . lists)
(or (not (pair? lists)) ; 0-ary case
(let lp ((s1 (car lists)) (rest (cdr lists)))
(or (not (pair? rest))
(let ((s2 (car rest)) (rest (cdr rest)))
(and (or (eq? s2 s1); Fast path
(%lset2<= = s1 s2)) ; Real test
(lp s2 rest)))))))
(define (lset= = . lists)
(or (not (pair? lists)) ; 0-ary case
(let lp ((s1 (car lists)) (rest (cdr lists)))
(or (not (pair? rest))
(let ((s2 (car rest))
(rest (cdr rest)))
(and (or (eq? s1 s2); Fast path
(and (%lset2<= = s1 s2) (%lset2<= = s2 s1))) ; Real test
(lp s2 rest)))))))
(define (append-map f . lists)
(apply append (apply map f lists)))
(define (concatenate lol)
(fold-right append '() lol))
;(define (last l) (car (reverse l))) ;;; pozdro997 -- LOL
(define (last-pair lis)
;(check-arg pair? lis last-pair)
(let lp ((lis lis))
(let ((tail (cdr lis)))
(if (pair? tail) (lp tail) lis))))
;;; ^ nie wiem czy mi sie to bardziej podoba jak moj 997 lol...
(define (last lis) (car (last-pair lis)))
(define (alist-delete key alist =)
(cond ((null? alist) '())
((= key (caar alist)) (cdr alist))
(else (cons (car alist) (alist-delete key (cdr alist) =)))))
;;; Map F across L, and save up all the non-false results.
(define (filter-map f lis1 . lists)
;(check-arg procedure? f filter-map)
(if (pair? lists)
(let recur ((lists (cons lis1 lists)))
(receive (cars cdrs) (%cars+cdrs lists)
(if (pair? cars)
(cond ((apply f cars) => (lambda (x) (cons x (recur cdrs))))
(else (recur cdrs))) ; Tail call in this arm.
'())))
;; Fast path.
(let recur ((lis lis1))
(if (null-list? lis) lis
(let ((tail (recur (cdr lis))))
(cond ((f (car lis)) => (lambda (x) (cons x tail)))
(else tail)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (lset-intersection = lis1 . lists)
(let ((lists (delete lis1 lists eq?))) ; Throw out any LIS1 vals.
(cond ((any null-list? lists) '()); Short cut
((null? lists) lis1); Short cut
(else (filter (lambda (x)
(every (lambda (lis) (member= x lis =)) lists))
lis1)))))
| true |
34747f9c04ff1a1058513b2568f240b42189401f
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/runtime/remoting/internal-remoting-services.sls
|
6d6e9bf1d8d7da87b3cc61ae1cd2e8be11e8f498
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,616 |
sls
|
internal-remoting-services.sls
|
(library (system runtime remoting internal-remoting-services)
(export new
is?
internal-remoting-services?
remoting-trace
get-cached-soap-attribute
remoting-assert
debug-out-chnl
set-server-identity)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Runtime.Remoting.InternalRemotingServices
a
...)))))
(define (is? a)
(clr-is System.Runtime.Remoting.InternalRemotingServices a))
(define (internal-remoting-services? a)
(clr-is System.Runtime.Remoting.InternalRemotingServices a))
(define-method-port
remoting-trace
System.Runtime.Remoting.InternalRemotingServices
RemotingTrace
(static: System.Void System.Object[]))
(define-method-port
get-cached-soap-attribute
System.Runtime.Remoting.InternalRemotingServices
GetCachedSoapAttribute
(static:
System.Runtime.Remoting.Metadata.SoapAttribute
System.Object))
(define-method-port
remoting-assert
System.Runtime.Remoting.InternalRemotingServices
RemotingAssert
(static: System.Void System.Boolean System.String))
(define-method-port
debug-out-chnl
System.Runtime.Remoting.InternalRemotingServices
DebugOutChnl
(static: System.Void System.String))
(define-method-port
set-server-identity
System.Runtime.Remoting.InternalRemotingServices
SetServerIdentity
(static:
System.Void
System.Runtime.Remoting.Messaging.MethodCall
System.Object)))
| true |
a357f2b07bc2dc3546fa256c96eb5d4309f160c1
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System.Xml/system/xml/schema/xml-atomic-value.sls
|
8ff4c5ad57f82abdce51d0827ae34b99e3355dcd
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,330 |
sls
|
xml-atomic-value.sls
|
(library (system xml schema xml-atomic-value)
(export is?
xml-atomic-value?
value-as
clone
to-string
is-node?
typed-value
value
value-as-boolean?
value-as-date-time
value-as-double
value-as-int
value-as-long
value-type
xml-type)
(import (ironscheme-clr-port))
(define (is? a) (clr-is System.Xml.Schema.XmlAtomicValue a))
(define (xml-atomic-value? a)
(clr-is System.Xml.Schema.XmlAtomicValue a))
(define-method-port
value-as
System.Xml.Schema.XmlAtomicValue
ValueAs
(System.Object System.Type System.Xml.IXmlNamespaceResolver))
(define-method-port
clone
System.Xml.Schema.XmlAtomicValue
Clone
(System.Xml.Schema.XmlAtomicValue))
(define-method-port
to-string
System.Xml.Schema.XmlAtomicValue
ToString
(System.String))
(define-field-port
is-node?
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
IsNode
System.Boolean)
(define-field-port
typed-value
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
TypedValue
System.Object)
(define-field-port
value
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
Value
System.String)
(define-field-port
value-as-boolean?
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
ValueAsBoolean
System.Boolean)
(define-field-port
value-as-date-time
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
ValueAsDateTime
System.DateTime)
(define-field-port
value-as-double
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
ValueAsDouble
System.Double)
(define-field-port
value-as-int
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
ValueAsInt
System.Int32)
(define-field-port
value-as-long
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
ValueAsLong
System.Int64)
(define-field-port
value-type
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
ValueType
System.Type)
(define-field-port
xml-type
#f
#f
(property:)
System.Xml.Schema.XmlAtomicValue
XmlType
System.Xml.Schema.XmlSchemaType))
| false |
51aad244e81f9e57be31ba3659db6f436689ab7e
|
43612e5ed60c14068da312fd9d7081c1b2b7220d
|
/tools/benchtimes/prefix/ChezScheme.scm
|
3e838b610a56159d5b253f62dfbdf19f46c0fe53
|
[
"BSD-3-Clause"
] |
permissive
|
bsaleil/lc
|
b1794065183b8f5fca018d3ece2dffabda6dd9a8
|
ee7867fd2bdbbe88924300e10b14ea717ee6434b
|
refs/heads/master
| 2021-03-19T09:44:18.905063 | 2019-05-11T01:36:38 | 2019-05-11T01:36:38 | 41,703,251 | 27 | 1 |
BSD-3-Clause
| 2018-08-29T19:13:33 | 2015-08-31T22:13:05 |
Scheme
|
UTF-8
|
Scheme
| false | false | 3,430 |
scm
|
ChezScheme.scm
|
;(declare (standard-bindings) (extended-bindings) (block))
;------------------------------------------------------------------------------
; Macros...
(define-syntax def-macro
(syntax-rules ()
((k (name . args) body ...)
(def-macro name (lambda args body ...)))
((k name transformer)
(define-syntax name
(lambda (stx)
(syntax-case stx ()
((l . sv)
(let* ((v (syntax->datum (syntax sv)))
(e (apply transformer v)))
(if (eq? (void) e)
(syntax (void))
(datum->syntax (syntax l) e))))))))))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
;)
;)
;------------------------------------------------------------------------------
;INSERTCODE
;------------------------------------------------------------------------------
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(newline)
(let* ((run (apply run-maker args))
(result (time (run-bench name count ok? run))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline)))))
(define (fatal-error . args)
(for-each display args)
(newline)
(exit 1))
(define (call-with-output-file/truncate filename proc)
(call-with-output-file filename proc))
| true |
d61ebb2e17c7129f469f12f474c0de6ea64f907e
|
65c11016738aec7f1dbebb590e7b4377e2d4278b
|
/GrammarCompiler/scheme/emit-scheme.ss
|
5711963ad1fc5c5680a00517739a5f2461c188f3
|
[] |
no_license
|
hgztheyoung/P423-framework-public
|
4014d87ba68cacf2d7b2081564a88db6992f41d1
|
187c902e0b4d08f666b27ce5e208cf13663b9f67
|
refs/heads/master
| 2021-01-16T22:53:02.637616 | 2012-07-08T05:09:05 | 2012-07-08T05:09:05 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 334 |
ss
|
emit-scheme.ss
|
(library (GrammarCompiler scheme emit-scheme)
(export emit-scheme)
(import (chezscheme))
(define emit-scheme
(lambda (x)
(scheme-boilerplate)
(newline)
(pretty-print x)))
(define scheme-boilerplate
(lambda ()
(pretty-print
'(import (Framework match)
(Framework prims)))))
)
| false |
e03c79aa8f2743502e59508324fd613edda3ef95
|
c763eaf97ffd7226a70d2f9a77465cbeae8937a8
|
/scheme/sqlite3/oop.scm
|
4a0f738c8c3f772365c8006c41b46000ec6cd435
|
[] |
no_license
|
jhidding/crossword
|
66907f12e87593a0b72f234ebfabbd2fb56dae9c
|
b3084b6b1046eb0a996143db1a144fd32379916f
|
refs/heads/master
| 2020-12-02T19:33:08.677722 | 2017-08-21T21:07:43 | 2017-08-21T21:07:43 | 96,357,240 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,479 |
scm
|
oop.scm
|
(library (sqlite3 oop)
(export <database> <statement> with *enter* *exit*
step column bind prepare prepare-all execute-script open-database query)
(import (rnrs (6))
; (srfi srfi-88)
(ice-9 format)
(oop goops)
(only (guile) string-null?)
(only (srfi srfi-1) unfold)
(cut)
(contexts)
(functional)
(sqlite3 defines)
(sqlite3 wrapped)
(tables tables)
(tables vector-tools))
(define-class <pointer> ()
(handle #:accessor handle #:init-keyword #:handle))
(define-class <database> (<pointer>))
(define-class <statement> (<pointer>))
(define (open-database filename)
(make <database> #:handle (sqlite-open filename)))
(define-method (*exit* (db <database>) (error <top>))
(when error
(format #t "SQLite error: ~a~%" (sqlite-errmsg (handle db))))
(sqlite-close (handle db))
(when error
(raise-continuable error)))
(define-method (*exit* (stmt <statement>) (error <top>))
(sqlite-finalize (handle stmt)))
(define-generic prepare)
(define-generic step)
(define-generic column)
(define-generic bind)
(define-generic query)
(define-generic prepare-all)
(define-generic execute-script)
(define-generic reset)
(define-method (prepare (db <database>) (source <string>))
(receive (errc stmt rest) (sqlite-prepare (handle db) source)
(if (= errc SQLITE_OK)
(make <statement> #:handle stmt)
(error 'prepare "Error preparing SQL statement." errc source))))
(define-method (execute-script (db <database>) (source <string>))
(unless (string-null? source)
(receive (errc stmt rest) (sqlite-prepare (handle db) source)
(if (= errc SQLITE_OK)
(begin
(with (stmt (make <statement> #:handle stmt))
(step stmt))
(execute-script db rest))
(error 'prepare-all "Error preparing SQL statement." errc source)))))
(define-method (step (stmt <statement>))
(sqlite-step (handle stmt)))
(define-method (column (stmt <statement>) (n <integer>))
(sqlite-column (handle stmt) n))
(define-method (column-count (stmt <statement>))
(sqlite-column-count (handle stmt)))
(define-method (column-name (stmt <statement>) (index <integer>))
(sqlite-column-name (handle stmt) index))
(define-method (bind (stmt <statement>) (n <integer>) (value <top>))
(sqlite-bind (handle stmt) n value))
(define-method (bind (stmt <statement>) (name <string>) (value <top>))
(let ((index (sqlite-bind-parameter-index (handle stmt) name)))
(sqlite-bind (handle stmt) index value)))
(define-method (reset (stmt <statement>))
(sqlite-reset (handle stmt)))
(define-method (query (stmt <statement>))
(let* ((n (column-count stmt))
(header (vector-map (cut column-name stmt <>)
(vector-range n)))
(get-row (lambda ()
(vector-map (cut column stmt <>) (vector-range n))))
(data (let loop ((result '())
(errc (step stmt)))
(cond
((= errc SQLITE_ROW) (loop (cons (get-row) result) (step stmt)))
((= errc SQLITE_DONE) (reverse result))
(else (error 'query "Error stepping statement." errc))))))
(make <table> #:header header #:data data)))
)
| false |
a14696bbacf368fee3aee5debc419eb83ac1d069
|
87f1e27952a387ff6a7d0625169d9a4f6cd960b2
|
/guix/scripts/workflow.scm
|
811791126bfa23a6a063de2a8bc3dfaef89597cb
|
[] |
no_license
|
guixwl/gwl
|
f5d21ca3563eed71e5cabb076f783fab63309cd1
|
036a6e043b9ee010b0ca7eaa5bd1381555385808
|
refs/heads/master
| 2020-03-17T23:42:10.633451 | 2018-03-11T11:22:16 | 2018-05-17T10:11:40 | 134,056,393 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,169 |
scm
|
workflow.scm
|
;;; Copyright © 2016, 2017, 2018 Roel Janssen <[email protected]>
;;; Copyright © 2018 Ricardo Wurmus <[email protected]>
;;;
;;; This program is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(define-module (guix scripts workflow)
#:use-module (gwl web-interface)
#:use-module (guix ui)
#:use-module (guix scripts)
#:use-module (guix utils)
#:use-module (guix process-engines)
#:use-module (guix workflows)
#:use-module (guix workflows graph)
#:use-module (gnu workflows)
#:use-module (ice-9 match)
#:use-module (ice-9 vlist)
#:use-module (srfi srfi-37)
#:use-module (srfi srfi-1)
#:export (guix-workflow))
(define (show-help)
(for-each
(lambda (line) (display line) (newline))
'("Usage: guix workflow [OPTION]..."
"Run multiple predefined computational process in a workflow"
""
" -i, --input=LOCATION set LOCATION as input for a workflow"
" -o, --output=LOCATION set LOCATION as output for a workflow"
" -e, --engine=ENGINE set ENGINE for offloading to a cluster"
" -l, --list-available list available processes"
" -p, --prepare=WORKFLOW Prepare to run WORKFLOW"
" -r, --run=WORKFLOW Run WORKFLOW"
" -s, --search=REGEXP search in synopsis and description using REGEXP"
" -g, --graph=WORKFLOW Output the workflow in Dot-format"
" -w, --web-interface Start the web interface"
" -h, --help display this help and exit"
" -V, --version display version information and exit"
"")))
(define (show-available-workflows args)
"Display available workflows."
(format #t "Available workflows:~%")
(let ((wfs (fold-workflows
(lambda (p r)
(if (string= (workflow-version p) "")
(vhash-cons (format #f "~a" (workflow-name p)) p r)
(vhash-cons (format #f "~a (~a)"
(workflow-name p)
(workflow-version p)) p r)))
vlist-null)))
(vlist-for-each (lambda (pair)
(format #t " * ~a~%" (car pair)))
wfs))
(newline))
(define %options
;; List of command-line options.
(list (option '(#\h "help") #f #f
(lambda args (show-help) (exit 0)))
(option '(#\V "version") #f #f
(lambda args (show-version-and-exit "guix process")))
(option '(#\e "engine") #t #f
(lambda (opt name arg result)
(alist-cons 'engine arg
(alist-delete 'engine result))))
(option '(#\i "input") #t #f
(lambda (opt name arg result)
(alist-cons 'input arg
(alist-delete 'input result))))
(option '(#\o "output") #t #f
(lambda (opt name arg result)
(alist-cons 'output arg
(alist-delete 'output result))))
(option '(#\p "prepare") #t #f
(lambda (opt name arg result)
(alist-cons 'query 'prepare
(alist-cons 'value arg
(alist-delete 'prepare result)))))
(option '(#\r "run") #t #f
(lambda (opt name arg result)
(alist-cons 'query 'run
(alist-cons 'value arg
(alist-delete 'run result)))))
(option '(#\g "graph") #t #f
(lambda (opt name arg result)
(alist-cons 'query 'graph
(alist-cons 'value arg
(alist-delete 'graph result)))))
(option '(#\s "search") #t #f
(lambda (opt name arg result)
(alist-cons 'query 'search
(alist-cons 'value arg
(alist-delete 'search result)))))
(option '(#\l "list-available") #f #f
(lambda args
(show-available-workflows args)))
(option '(#\w "web-interface") #f #f
(lambda args
(run-web-interface)))))
(define %default-options
`((engine . "bash-engine")))
;;;
;;; Entry point.
;;;
(define (guix-workflow . args)
(define (parse-options)
;; Return the alist of option values.
(args-fold* args %options
(lambda (opt name arg result)
(leave (G_ "~A: unrecognized option~%") name))
(lambda (arg result)
(when (assq 'argument result)
(leave (G_ "~A: extraneous argument~%") arg))
(alist-cons 'argument arg result))
%default-options))
(let ((opts (parse-options)))
(match (assoc-ref opts 'query)
;; Handle searching for a process.
;; ----------------------------------------------------------------------
('search
(let* ((procs (find-workflows (assoc-ref opts 'value))))
(unless (null? procs)
(vlist-for-each (lambda (proc)
(print-workflow-record (cdr proc) #t)) procs)))
#t)
;; Handle preparing to running processes.
;; ----------------------------------------------------------------------
('prepare
;; TODO: Deal with the situation wherein multiple processes
;; with the same name are defined.
(let* ((wfs (find-workflow-by-name (assoc-ref opts 'value)))
(wf (if (null? wfs) '() (car wfs)))
(engine-name (assoc-ref opts 'engine))
(wf-name (assoc-ref opts 'value)))
(when (or (not engine-name)
(not wf-name))
(leave (G_ "Please provide --engine and --run arguments.~%")))
(when (not (workflow? wf))
(leave (G_ "Cannot find a workflow with name ~s.~%") wf-name))
(let ((engine (find-engine-by-name engine-name)))
(when (not engine)
(leave (G_ "The engine ~s is not available.~%") engine-name))
(workflow-prepare wf engine)))
#t)
;; Handle running processes.
;; ----------------------------------------------------------------------
('run
;; TODO: Deal with the situation wherein multiple processes
;; with the same name are defined.
(let* ((wfs (find-workflow-by-name (assoc-ref opts 'value)))
(wf (if (null? wfs) '() (car wfs)))
(engine-name (assoc-ref opts 'engine))
(wf-name (assoc-ref opts 'value)))
(when (or (not engine-name)
(not wf-name))
(leave (G_ "Please provide --engine and --run arguments.~%")))
(when (not (workflow? wf))
(leave (G_ "Cannot find a workflow with name ~s.~%") wf-name))
(let ((engine (find-engine-by-name engine-name)))
(when (not engine)
(leave (G_ "The engine ~s is not available.~%") engine-name))
(workflow-run wf engine)))
#t)
('graph
(let* ((wfs (find-workflow-by-name (assoc-ref opts 'value)))
(wf (if (null? wfs) '() (car wfs))))
(if (null? wf)
(leave (G_ "Could not find the workflow to graph.~%"))
(begin
(display (workflow->dot wf))
(newline))))
#t)
;; Handle (or don't handle) anything else.
;; ----------------------------------------------------------------------
(_ #t))))
| false |
a538ff67c32f989662a3a9ac73335835ae220b67
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/security/cryptography/hmacsha512.sls
|
9ca096711294112ea29d1d2db33c0ec82a64d53d
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 812 |
sls
|
hmacsha512.sls
|
(library (system security cryptography hmacsha512)
(export new
is?
hmacsha512?
produce-legacy-hmac-values?-get
produce-legacy-hmac-values?-set!
produce-legacy-hmac-values?-update!)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.Security.Cryptography.HMACSHA512 a ...)))))
(define (is? a) (clr-is System.Security.Cryptography.HMACSHA512 a))
(define (hmacsha512? a)
(clr-is System.Security.Cryptography.HMACSHA512 a))
(define-field-port
produce-legacy-hmac-values?-get
produce-legacy-hmac-values?-set!
produce-legacy-hmac-values?-update!
(property:)
System.Security.Cryptography.HMACSHA512
ProduceLegacyHmacValues
System.Boolean))
| true |
b7885c643474bab804b6f4a1a7e4fc44c5a55fd0
|
58381f6c0b3def1720ca7a14a7c6f0f350f89537
|
/Chapter 2/2.2/Ex2.24.scm
|
22196b0c6c287ef474fcbb62cb37de3c295e46a1
|
[] |
no_license
|
yaowenqiang/SICPBook
|
ef559bcd07301b40d92d8ad698d60923b868f992
|
c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a
|
refs/heads/master
| 2020-04-19T04:03:15.888492 | 2015-11-02T15:35:46 | 2015-11-02T15:35:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 123 |
scm
|
Ex2.24.scm
|
#lang planet neil/sicp
(list 1 (list 2 (list 3 4)))
; (mcons 1 (mcons (mcons 2 (mcons (mcons 3 (mcons 4 '())) '())) '()))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.