Category:Initlib: Difference between revisions
Improved display of source code, enabled syntax highlighting, and fixed sloppy formatting and typos.
(→Library: restructuring) |
(Improved display of source code, enabled syntax highlighting, and fixed sloppy formatting and typos.) |
||
(7 intermediate revisions by 2 users not shown) | |||
Line 1:
Here is a library of functions tested in
<syntaxhighlight lang="shell" inline>
ghostscript -q -dNODISPLAY -c '(initlib.ps) run'
</syntaxhighlight>
== <code>initlib.ps</code> ==
<
%!PS
% conventions: parameter names with let begins with .
Line 18:
% some predicates.
/eq? {eq
/list? {dup type /arraytype eq?}.
/leaf? {list? not}.
/empty? {dup length 0 eq?}.
/zero? {dup 0 eq?}.
% stack invariant, execute any predicate and
% leave stack untouched except for answer.
[/.pred] let*
end}.
% stacky functions
Line 53 ⟶ 64:
/uncons {getname getbody}.
/concat {exch [ rup aload pop counttomark -1 roll aload pop ] }.
% make a unit list.
/unit {1 array astore cvx}.
Line 70 ⟶ 82:
/find {
4 dict begin
end}.
▲/zip {
/transpose {
[ exch {
{ {empty? exch pop} map all?} {pop exit} ift
[ exch {} {uncons {exch cons} dip exch} fold counttomark 1 roll] uncons
} loop ] {reverse} map
}.
/zip {[rup] transpose}.
% [[1 2 3 4 ] [5 6 7 8] [9 10 11 12]] transpose
/all? {
{
{empty?} ? {pop true exit} if
uncons {?} dip exch not {pop false exit} if
} loop
}.
% 1 {{10 gt} {5 gt} {0 gt}} any?
/any? {
{
{empty?} ? {pop false exit} if
uncons {?} dip exch {pop true exit} if
} loop
}.
/pipe {
{
{empty?} ? {pop exit} if
uncons {i} dip
} loop
}.
% 1 {{2 *} {3 *} {5 *}} pipe
/collect {
{
{empty?} ? {pop exit} if
uncons {?} dip
} loop
}.
% 1 {{2 *} {3 *} {5 *}} collect
% do on all elements of a tree.
/treemap {
[/.tree /.rec] let
end}.
Line 97 ⟶ 140:
% ift - allow stack invariant if condition
/ift {
[/.if /.then] let
▲ 4 dict begin
/.if ' ?
▲ count array astore /.stack exch def
▲ /_restore {clear .stack aload pop}.
▲ .stack aload pop .if {
▲ _restore .then
end}.
% ift - allow stack invariant ifelse condition
/ifte {
[/.if /.then /.else] let
4 dict begin▼
/.if ' ?
end}.
% switch statement.
Line 126 ⟶ 155:
/dip {
[/.v /.q] let
end}.
/apply {exec}.
Line 133 ⟶ 162:
/linrec {
[/.if /.then /.rec1 /.rec2] let
end}.
/binrec {
[/.if /.then /.rec1 /.rec2] let
end}.
/genrec {
[/.if /.then /.rec1 /.rec2] let
end}.
Line 163 ⟶ 192:
/primrec {
5 dict begin
[/.param /.then /.rec] let*
end}.
/cvstr {
/elements exch def
/len elements length def
/str len string def
/i 0 def
{
i len ge { exit } if
str i
% The element of the array, as a hexadecimal string.
% If it exceeds 16#FF, this will fail with a rangecheck.
elements i get cvi
put
/i i 1 add def
} loop
str
end
} def
Line 183 ⟶ 231:
/puts {= (\n) print flush}.
/, {(=============\n)
% set the prompt to something else so that we know initlib is loaded.
/prompt {(>| ) print flush} bind def</syntaxhighlight>
|