newLISP®

For macOS, GNU Linux, Unix and Windows

ユーザー マニュアルとリファレンス v.10.7.5

User Manual and Reference v.10.7.5






Copyright © 2019 Lutz Mueller www.nuevatec.com. All rights reserved.
Japanese translations copyright © 2019 short story または 晴耕雨読な日々

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License,
Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts,
and no Back-Cover Texts. A copy of the license is included in the section entitled GNU Free Documentation License.
The accompanying software is protected by the GNU General Public License V.3, June 2007.
newLISP is a registered trademark of Lutz Mueller.



Contents(目次)

Users Manual(ユーザー マニュアル)

  1. Introduction(イントロダクション)
  2. Deprecated functions and future changes(廃止される関数と将来の変更)
  3. Interactive Lisp mode(インターラクティブ Lisp モード)
  4. Command line options(コマンド ライン オプション)
  5. Startup, directories, environment(スタートアップ、ディレクトリ、環境)
  6. Extending newLISP with shared libraries(共有ライブラリによる newLISP の拡張)
  7. newLISP as a shared library(共有ライブラリとしての newLISP)
  8. Evaluating newLISP expressions(newLISP 式の評価)
  9. Lambda expressions in newLISP(newLISP におけるラムダ式)
  10. nil, true, cons and () in newLISP(newLISP の niltruecons()
  11. Arrays(アレイ)
  12. Indexing elements of strings, lists and arrays(文字列、リスト、アレイの要素指定)
  13. Destructive versus non-destructive functions(破壊的 対 非破壊的関数)
  14. Early return from functions, loops, blocks(関数、ループ、ブロックからの早期脱出)
  15. Dynamic and lexical scoping(ダイナミック・スコープとレキシカル・スコープ)
  16. Contexts(コンテキスト)
  17. The context default functor(コンテキスト・デフォルト・ファンクタ)
  18. Functional object-oriented programming(関数的オブジェクト指向プログラミング)
  19. Concurrent processing and distributed computing(並列処理と分散コンピューティング)
  20. JSON, XML, SXML and XML-RPC(JSON、XML、SXML と XML-RPC)
  21. Customization, localization and UTF-8(カスタマイズ、ローカライズと UTF-8)
  22. Commas in parameter lists(パラメータ リストのカンマ)

Function Reference(関数リファレンス)

  1. Syntax of symbol variables and numbers(シンボル変数と数値の構文)
  2. Data types and names in the reference(リファレンスでのデータ型と名前)
  3. Functions in groups(グループ毎の関数)
  4. Functions in alphabetical order(アルファベット順の関数)

    !  +-*/%  Ab  Ap  As  Ba  Ca  Cl  Co  Cu  De  Di  Do  En 
    Ex  Fi  Fl  Ga  Gl  In  La  Li  Ma  Mu  Net  New  Nt  Pa 
    Pr  Ra  Rea  Reg  Sea  Seq  Sl  St  Sy  Ti  Tr  Ut  Wr 

Appendix(付録)


 )


newLISP User Manual

1. Introduction(イントロダクション)

newLISP は、Lisp の主要構成要素:リストシンボルラムダ式 に焦点を合わせています。 これらに newLISP はアレイ とリストやアレイ上の 暗黙の要素指定ダイナミック(訳注:動的ともいう) 及び レキシカル(訳注:静的または構文的ともいう)スコープ を追加しています。 レキシカル・スコープは、コンテキスト と呼ばれる独立した名前空間を使って実装しています。(訳注:名前空間 コンテキスト は、ダイナミック・スコープで fexpr を使う時の安全性を提供します。fexpr とは、引数が評価されずに渡される関数のこと。newlLISP では define-macro を使って定義します)
newLISP focuses on the core components of Lisp: lists, symbols, and lambda expressions. To these, newLISP adds arrays, implicit indexing on lists and arrays, and dynamic and lexical scoping. Lexical scoping is implemented using separate namespaces called contexts.

その結果、ほとんどの Scheme 実装よりも小さくありながら、約 350個 の組込関数を持つという学びやすい Lisp となっています。 newLISP のサイズは BSD システムで 200k 強でありながら、最も一般的な Unix システム C ライブラリのみを使い、高いポータビリティを持って構築されています。 ロードも素早く、メモリ消費もわずかです。 newLISP は他の一般的なスクリプト用言語と同等かそれ以上に早く、リソースも少ししか使いません。
The result is an easier-to-learn Lisp that is even smaller than most Scheme implementations, but which still has about 350 built-in functions. Not much over 200k in size on BSD systems, newLISP is built for high portability using only the most common Unix system C-libraries. It loads quickly and has a small memory footprint. newLISP is as fast or faster than other popular scripting languages and uses very few resources.

組込とユーザ定義関数の両方とも、変数と一緒に、同じグローバル・シンボル木を共有し、同じ関数として扱われます。 また、ラムダ式とユーザ定義関数は、他のリスト式と同じように処理できます。
Both built-in and user-defined functions, along with variables, share the same global symbol tree and are manipulated by the same functions. Lambda expressions and user-defined functions can be handled like any other list expression.

newLISP は、レキシカルに分離されたコンテキスト(名前空間)を内部に持つダイナミック・スコープです。 newLISP のコンテキストは、様々な用途で使われます。 (1) プログラムのモジュール分割、 (2) FOOP (Functional Object Oriented Programming) での クラス 定義、 (3) 状態を持つ関数の定義(訳注:いわゆるクロージャ) (4) 連想キー → 値保存のためのハッシュ木生成等を可能にします。
newLISP is dynamically scoped inside lexically separated contexts (namespaces). Contexts in newLISP are used for multiple purposes. They allow (1) partioning of programs into modules, (2) the definition of Classes in FOOP (Functional Object Oriented Programming), (3) the definition of functions with state and (4) the creation of Hash trees for associative key → value storage.

newLISP の効率的な赤黒木(訳注:英語版は、こちら)の実装は、性能劣化なしに数百万のシンボルを処理できます。
newLISP's efficient red-black tree implementation can handle millions of symbols in namespaces or hashes without degrading performance.

newLISP は、伝統的な非同期ガベージコレクションを使用せずに、メモリの割当と回収を自動的に行ないます(エラー条件下を除いて)。 全てのオブジェクトは——コンテキスト、組込プリミティブ、シンボルを除いて——値として渡され、一度だけ参照されます。 オブジェクトは、生成において遅延削除が予定されており、Lisp セルを新規オブジェクト生成用に再利用します。 これらの結果として、伝統的なガベージコレクションに見られる休止は起こらず、予測可能な処理時間をもたらします。 newLISP の独創的な自動メモリ管理は、最も早いインターラクティブ Lisp をもたらします。 それは、他の Lisp 以上に、データ = プログラム パラダイムと完全な自己リフレクション実装をもたらします。
newLISP allocates and reclaims memory automatically, without using traditional asynchronous garbage collection. All objects — except for contexts, built-in primitives, and symbols — are passed by value and are referenced only once. Upon creation objects are scheduled for delayed deletion and Lisp cells are recycled for newly created objects. This results in predictable processing times without the pauses found in traditional garbage collection. newLISP's unique automatic memory management makes it the fastest interactive Lisp available. More than any other Lisp, it implements the data equals program paradigm and full self reflection.

newLISP の組込関数は、様々な形態を持ち、多様なデータ型とオプション・パラメータを受け入れます。 これは学習や実装に必要な関数と構文形態の数を劇的に減らします。 高級関数が多数用意されており、分布計算、並行プロセス、財務数学、統計、人工知能アプリケーションに利用できます。
Many of newLISP's built-in functions are polymorphic and accept a variety of data types and optional parameters. This greatly reduces the number of functions and syntactic forms necessary to learn and implement. High-level functions are available for string and list processing, financial math, statistics, and Artificial Intelligence applications.

newLISP は複雑な入れ子 リストや多次元 アレイ構造内の要素を変更・挿入・削除する関数を多数持っています。
newLISP has functions to modify, insert, or delete elements inside complex nested lists or multi-dimensional array structures.

newLISP では文字列に null 文字を含ませることができ、バイナリ・データ処理にほとんどの文字列操作関数を使えます。
Because strings can contain null characters in newLISP, they can be used to process binary data with most string manipulating functions.

newLISP は共有ライブラリ・インターフェースによる拡張も可能で、外部バイナリ・データ構造のデータをアクセスする関数を導入することができます。 配布物には、一般的なデータベース API 群を導入するためのモジュール群が入っています。
newLISP can also be extended with a shared library interface to import functions that access data in foreign binary data structures. The distribution contains modules for importing popular C-library APIs.

newLISP の HTTP、TCP/IP、UDP ソケット・インターフェイスは、ネットワーク分散アプリケーションを書き易くします。 newLISP の組込 XML インターフェース は、テキスト処理機能—— Perl コンパチブル正規表現 (PCRE) とテキスト解析関数 ——と相まって、有用な CGI 処理ツールを提供します。 配布ソースに HTML フォーム処理例があります。 newLISP は、組込 http モード・オプションを使って、CGI 処理可能なウェブ・サーバーになります。
newLISP's HTTP, TCP/IP, and UDP socket interfaces make it easy to write distributed networked applications. Its built-in XML interface, along with its text-processing features — Perl Compatible Regular Expressions (PCRE) and text-parsing functions — make newLISP a useful tool for CGI processing. The source distribution includes examples of HTML forms processing. newLISP can be run a as a CGI capable web server using its built-in http mode option.

newLISP は、ネットワーク上の分散処理と一個以上のコアを持つ CPU 上の並列処理を支援する組込関数を持っています。
newLISP has built-in support for distributed processing on networks and parallel, concurrent processing on the same CPU with one or more processing cores.

配布ソースは、Linux, macOS/Darwin, BSD, 他の多くの Unix 類似品, MS Windows でコンパイル可能です。 newLISP は、完全な64ビット・メモリ・アドレッシング用の 64ビット LP64 アプリケーションとしてもコンパイルできます。
The source distribution can be compiled for Linux, macOS/Darwin, BSDs, many other Unix flavors and MS Windows. newLISP can be compiled as a 64-bit LP64 application for full 64-bit memory addressing.

バージョン 10.5.7 から、newLISP は JavaScript にもコンパイルして、ウェブ・ブラウザ(訳注:JavaScript 版 newLISP の簡易 IDE に飛びます) で走らせることができます。
Since version 10.5.7, newLISP also can be compiled to JavaScript and run in a web browser.


Licensing

newLISP は GPL (General Public License) 第3版のもとでライセンスされます。 newLISP 文書は newLISP と一緒にパッケージされた他の文書と同様に GNU Free Documentation License のもとでライセンスされます。
newLISP are licensed under version 3 of the GPL (General Public License). The newLISP documentation as well as other documentation packaged with newLISP are licensed under the GNU Free Documentation License.


§ )

2. Deprecated functions since version 10.3.0(バージョン10.3.0 から廃止される関数)

バージョン 10.3.0 以降の newLISP は、新規関数 net-ipv を使って、ランタイムに IPv4 モードと IPv6 モードを切り替えることができます。 IPv6 モードで newLISP を開始するのに、-6 のコマンドライン・オプションが使えます。 IPv6 に移行後は、 -6 コマンドライン・スイッチは、IPv4 モードで開始するための -4 に変更されるでしょう。
Since version 10.3.0 newLISP can switch between IPv4 and IPv6 modes during run-time using the new net-ipv function. The -6 commandline option can be used to start newLISP in IPv6 mode. After transition to IPv6 the -6 commandline switch will be changed to -4 for starting up in IPv4 mode.

date-parse の古い書式 parse-date はまだ認識されますが、バージョン10.3.0 以降推奨されません。 古い書式は将来のバージョンで削除されます。
The old writing parse-date of date-parse is still recognized but deprecated since version 10.3.0. The old writing will be removed in a future version.

バージョン 10.4.2 以降、if-not は推奨されていません。将来のバージョンで削除される可能性があります。
Since version 10.4.2 if-not is deprecated and will be removed in a future version.

バージョン 10.4.6 以降の newLISP には、 JSON データをS式に翻訳する組込関数 json-parse があります。 そのため json.lsp モジュール・ファイルが配布から外されます。
Since version 10.4.6 newLISP has a built-in function json-parse for translating JSON data into S-expressions. The module file json.lsp is removed from the distribution.

バージョン 10.4.8 以降、桁数に制限のない整数がサポートされます。 これにより、GNU GMP モジュール である gmp.lsp は不要になります。
Since version 10.4.8 newLISP has built-in support for unlimited precision integers. This makes the GNU GMP module gmp.lsp obsolete.


§ )

3. Interactive Lisp mode(インターラクティブ Lisp モード)

Lisp を体験し、それを試す最も良い方法は、ターミナル・ウィンドウか、オペレーティング・システムのコマンド・シェルにおいて、対話モードを使うことです。 バージョン 10.3 から、newLISP の read-eval-print-loop (REPL) は複数行を受け付けます。
The best way to experience Lisp and experiment with it, is using interactive mode in a terminal window or operating system command shell. Since version 10.3, newLISP's read-eval-print-loop (REPL) accepts multi-line statements.

複数行の宣言文を入力するには、システム・プロンプトの後に空行で [enter] キーを打ちます。 複数行モードから出るには、再び、空行で [enter] キーを打ちます。 次の例では、コンピュータの出力が太文字で示されています:
To enter a multi-line statement hit the [enter] key on an empty line after the system prompt. To exit multi-line mode, hit the [enter] key again on an empty line. In the following example computer output is shown in bold letters:

> 
(define (foo x y)
    (+ x y))

(lambda (x y) (+ x y))
> (foo 3 4)
7
> 

複数行モードは、OSコマンド・ターミナル・ウィンドウかコマンド・シェルでのみ可能なことに注意してください。
Note, that multi-line mode is only possible in an OS command terminal window or command shell.

対話モードの Lisp はオペレーティング・システムのシェル・コマンドも受け付けます。 OS コマンドを入力するには、プロンプトの右直後に '!' 文字を入力し、シェル・コマンドを続けます:
Interactive Lisp mode can accept operating system shell commands. To hit an OS command enter the '!' character right after the prompt, immediately followed by the shell command:

> !ls *.html
CodePatterns.html		MemoryManagement.html	newLISPdoc.html
ExpressionEvaluation.html	manual_frame.html		newlisp_index.html
License.html			newLISP-10.3-Release.html	newlisp_manual.html
> 

この例では ls コマンドが入力され、現在のディレクトリの HTML ファイルが表示されています。 MS ウィンドウズ では、dir コマンドを同じ処理に使います。
In the example a ls shell command is entered to show HTML files in the current directory. On MS Windows a dir command could be used in the same fashion.

このモードはエディタ等の他のプログラムを呼び出すのにも使えます:
The mode can also be used to call an editor or any other program:

> !vi foo.lsp

この例では Vi エディタがプログラム "foo.lsp" を編集するために開いています。 エディタを離れた後のプログラムは load 宣言文を使って、走らせることができます。

The Vi editor will open to edit the program "foo.lsp". After leaving the editor the program could be run using a load statement:

> (load "foo.lsp")

これでプログラム foo.lsp が走ります。
The program foo.lsp is now run.

UNIX で端末やコマンド・シェルを使っている時は、tab を使って newLISP 組込関数を補完表示できます:
When using a Unix terminal or command shell, tab-expansion for built-in newLISP functions can be used:

> (pri
print       println     primitive?  
> (pri

このように、文字 (pri の入力後に [tab] キーを一回打てば、同じ文字で始まる組込関数が全て表示されます。 関数名の前に [tab] を二回打つと、全ての組込関数名が表示されます。
After entering the characters (pri hit the [tab] key once to show all the built-in functions starting with the same characters. When hitting [tab] twice before a function name has started, all built-in function names will be displayed.

ほとんどの Unix では、ホーム・ディレクトリにある .inputrc ファイルに次の行を含めることで、コマンダラインにおける括弧の一致が可能になります:
On most Unix, parenthesis matching can be enabled on the commandline by including the following line in the file .inputrc in the home directory:

set blink-matching-paren on

但し、全てのシステムの libreadline が、この動作の可能なバージョンになっているとは限りません。
Not all systems have a version of libreadline advanced enough for this to work.


§ )

4. Command-line options, startup and directories(コマンド ライン オプション)

Command line help summary(コマンド ライン ヘルプ要約)

コマンドラインから newLISP を開始する時、いくつかのスイッチとオプション及びソースを指定できます。 次の実行は:
When starting newLISP from the command-line several switches and options and source files can be specified. Executing:

newlisp -h

コマンドシェルで、次のようにオプションとスイッチの要約を出します:
in a command shell will produce the following summary of options and switches:

 -h this help (no init.lsp)
 -n no init.lsp (must be first)
 -x <source> <target> link (no init.lsp)
 -v version
 -s <stacksize>
 -m <max-mem-MB> cell memory
 -e <quoted lisp expression>
 -l <path-file> log connections
 -L <path-file> log all
 -w <working dir>
 -c no prompts, HTTP
 -C force prompts
 -t <usec-server-timeout>
 -p <port-no>
 -d <port-no> demon mode
 -http only
 -http-safe safe mode
 -6 IPv6 mode

コマンドラインのスイッチの前後で、ロードして実行するファイルを指定できます。 実行可能な newLISP プログラムが続くパラメータを利用するなら、 そのプログラムは (exit) 宣言文で終わっている必要があります。 そうでなければ、newLISP はコマンドラインのパラメータを、ロードして実行すべき追加の newLISP スクリプト(訳注:もしくは追加のコマンドライン・オプション)として解釈します。
Before or after the command-line switches, files to load and execute can be specified. If a newLISP executable program is followed by parameters, the program must finish with and (exit) statement, else newLISP will take command-line parameters as additional newLISP scripts to be loaded and executed.

Linux や他の Unix システム上で、newlispman ページ が見つかります:
On Linux and other Unix systems, a newlisp man page can be found:

man newlisp

これは、Linux/Unix シェルで man ページを表示します。
This will display a man page in the Linux/Unix shell.


Specifying files as URLs(URL としてのファイル指定)

newLISP はコマンドラインで指定されたファイルを、ロードして実行します。 ファイルはローカル・ファイル上のパス名か file:// URL のどちらか、 または HTTP サーバーが走っているリモート・ファイル・システム上の http:// URL で指定されます。 HTTP サーバー・モードで走っている newLISP も HTTP サーバーになります。
newLISP will load and execute files specified on the command-line. Files are specified with either their pathname or a file:// URL on the local file system or with a http:// URL on remote file systems running an HTTP server. That HTTP server can be newLISP running in HTTP server mode.

newlisp aprog.lsp bprog.lsp prog.lsp
newlisp http://newlisp.org/example.lsp
newlisp file:///usr/home/newlisp/demo.lsp

No loading of init.lsp(init.lsp のロード無し)

このオプションは、初期化ファイル init.lsp または .init.lsp のロードを抑制します。 これを動作させるには、第一オプションに指定されなければなりません:
This option suppresses loading of any present initialization file init.lsp or .init.lsp. In order to work, this must be the first option specified:

newlisp -n

初期化ファイルの詳細は The initialization file init.lsp(初期化ファイル init.lsp) で。
More about initialization files.


Stack size(スタック・サイズ)

newlisp -s 4000
newlisp -s 100000 aprog bprog
newlisp -s 6000 myprog
newlisp -s 6000 http://asite.com/example.lsp

上の例は、-s オプションを使って異なるスタック・サイズで newLISP を開始するのを示しているのと共に、 一つ以上の newLISP ソースファイルをロードする例と URL で指定されたファイルをロードする例を示しています。 スタック・サイズが指定されない時はデフォルトの 2048 になります。 一つのスタックにつき 80 バイトのメモリが予約されます。
The above examples show starting newLISP with different stack sizes using the -s option, as well as loading one or more newLISP source files and loading files specified by an URL. When no stack size is specified, the stack defaults to 2048. Per stack position about 80 bytes of memory are preallocated.


Maximum memory usage(最大メモリ使用量)

newlisp -m 128

この例では newLISP セル・メモリを 128 メガバイトに制限しています。 32 ビット newLISP では、各リスプ・セルは 16 バイト消費するので、 引数の 128 は最大 8,388,608 の newLISP セルを意味します。 この情報は sys-info で返るリストの第二要素にあります。 リスプ・セル量が newLISP で消費する唯一のメモリではありませんが、 動的メモリ使用量全体の良い指標になります。
This example limits newLISP cell memory to 128 megabytes. In 32-bit newLISP, each Lisp cell consumes 16 bytes, so the argument 128 would represent a maximum of 8,388,608 newLISP cells. This information is returned by sys-info as the list's second element. Although Lisp cell memory is not the only memory consumed by newLISP, it is a good estimate of overall dynamic memory usage.


Direct execution mode(直接実行モード)

newLISP 小品はコマンドラインから直接実行できます:
Small pieces of newLISP code can be executed directly from the command-line:

newlisp -e "(+ 3 4)"   7 ; On MS Windows and Unix

newlisp -e '(append "abc" "def")'   "abcdef" ; On Unix

引用符で囲まれた式が評価され、結果は標準出力 (STDOUT) に出力されます。 ほとんどの Unix システム・シェルでは、コマンド文字列の区切りにシングル・クォートが使えます。 -e と引用コマンド文字列の間にスペースが有ることに注意してください。
The expression enclosed in quotation marks is evaluated, and the result is printed to standard out (STDOUT). In most Unix system shells, single quotes can also be used as command string delimiters. Note that there is a space between -e and the quoted command string.


Logging I/O(I/O のログ出力化)

どのモードの newLISP でも -l-L オプションで始めれば、ログの書き込みができます。 走っている newLISP のモードによって、ログ・ファイルに書き込まれる内容が変わります。 どちらのオプションでもログ・ファイルのパス指定が必要です。 パスには相対パスが使え、-l-L オプションと、くっついていても離れていても構いません。 ファイルが存在していないなら、最初にログ出力を書き出す時点で生成されます。
In any mode, newLISP can write a log when started with the -l or -L option. Depending on the mode newLISP is running, different output is written to the log file. Both options always must specify the path of a log-file. The path may be a relative path and can be either attached or detached to the -l or -L option. If the file does not exist, it is created when the first logging output is written.

newlisp -l./logfile.txt -c

newlisp -L /usr/home/www/log.txt -http -w /usr/home/www/htpdocs

次の表に示されているのは、状況別のログ項目です:
The following table shows the items logged in different situations:

logging modecommand-line and net-eval with -cHTTP server with -http
newlisp -l log only input and network connections log only network connections
newlisp -L log also newLISP output (w/o prompts) log also HTTP requests

-l-Lオプションの後に指定されたファイルに、ログ出力が全て書き込まれます。
All logging output is written to the file specified after the -l or -L option.


Specifying the working directory(作業ディレクトリの指定)

-w オプションは、newLISP のスタートアップ後の初期作業ディレクトリを指定します:
The -w option specifies the initial working directory for newLISP after startup:

newlisp -w /usr/home/newlisp

ディレクトリ・パスの付いていないファイルは全て、 -w オプションで指定されたパスに振り向けられます。
All file requests without a directory path will now be directed to the path specified with the -w option.


Suppressing the prompt and HTTP processing(プロンプトの抑制と HTTP 処理)

コマンドライン・プロンプトと最初に表示されるコピーライトが抑制されます:
The command-line prompt and initial copyright banner can be suppressed:

newlisp -c

ログ状態でないなら、待ち受け(listen)と接続のメッセージも抑制されます。 -c オプションは他のプログラムから newLISP を制御する時に便利であり、 net-eval サーバーとして設定する時は必須です。
Listen and connection messages are suppressed if logging is not enabled. The -c option is useful when controlling newLISP from other programs; it is mandatory when setting it up as a net-eval server.

-c オプションは、 CGI プロセシングはもちろん、 HTTP GETPUTPOSTDELETE 要求リクエストに返答する newLISP サーバー・ノードも可能にします。 -w-d と一緒に -c オプションを使うと、 newLISP はスタンドアローンの httpd ウェブ・サーバーになります:
The -c option also enables newLISP server nodes to answer HTTP GET, PUT, POST and DELETE requests, as well as perform CGI processing. Using the -c option, together with the -w and -d options, newLISP can serve as a standalone httpd webserver:

newlisp -c -d 8080 -w /usr/home/www

Unix 機において、newLISP を inetdxinetd が可能なサーバーとして走らせる時は、次のようにして使います:
When running newLISP as a inetd or xinetd enabled server on Unix machines, use:

newlisp -c -w /usr/home/www

-c モードで、newLISP は HTTP と同様なコマンドライン要求リクエストnet-eval 要求リクエストを処理します。 このモードで newLISP を走らせるのは、ファイアーウォールで守られたマシン上でのみ推奨されます。 インターネットに開放され、アクセスも可能なマシン上では、このモードで走らせるべきではありません。 net-eval やコマンドラインのような要求リクエストの処理を抑制するために、より安全な -http オプションを使ってください。
In -c mode, newLISP processes command-line requests as well as HTTP and net-eval requests. Running newLISP in this mode is only recommended on a machine behind a firewall. This mode should not be run on machines open and accessible through the Internet. To suppress the processing of net-eval and command-line–like requests, use the safer -http option.


Forcing prompts in pipe I/O mode(パイプ I/O モードでの強制プロンプト)

大文字 C は、 Emacs エディタ 内においてパイプ I/O モードで newLISP を走らせている時、プロンプトを強制します:
A capital C forces prompts when running newLISP in pipe I/O mode inside the Emacs editor:

newlisp -C

評価による戻り値のコンソール出力を抑制するには silent を使ってください。
To suppress console output from return values from evaluations, use silent.


newLISP as a TCP/IP server(TCP/IP サーバーとして newLISP)

newlisp some.lsp -p 9090

この例は newLISP が TCP/IP ソケット接続上でコマンドを待ち受け(listen)する方法を示しています。 この場合、標準 I/O は -p オプションで指定されるポートへリダイレクトされています。 some.lsp はオプション・ファイルで、 スタートアップ時、接続が開始し待ち受け(listen)する前にロードされます。
This example shows how newLISP can listen for commands on a TCP/IP socket connection. In this case, standard I/O is redirected to the port specified with the -p option. some.lsp is an optional file loaded during startup, before listening for a connection begins.

-p オプションは、主に別のアプリケーションから newLISP を制御する時に使われます。別のアプリケーションとは newLISP GUI フロントエンドや他の言語で書かれたプログラムのようなものです。 制御しているクライアントが接続を閉じると、newLISP は直ちに終了します。
The -p option is mainly used to control newLISP from another application, such as a newLISP GUI front-end or a program written in another language. As soon as the controlling client closes the connection, newLISP will exit.

サーバーとして走っている newLISP のテストに telnet アプリケーションが使えます。 最初に次のように入力します:
A telnet application can be used to test running newLISP as a server. First enter:

newlisp -p 4711 &

Unix シェルにおいて & はプロセスをバックグラウンドで走らせることを意味します。 Windows では、& 無しでサーバー・プロセスをフォアグラウンドで開始して、 telnet アプリケーション用に二つ目のコマンド・ウィンドウを開いてください。 telnet を接続します:
The & indicates to a Unix shell to run the process in the background. On Windows, start the server process without the & in the foreground and open a second command window for the telnet application. Now connect with a telnet:

telnet localhost 4711

接続すると、newLISP サインオン表示とプロンプトが現れます。 4711 の代わりに、他のポート番号を使うこともできます。
If connected, the newLISP sign-on banner and prompt appear. Instead of 4711, any other port number could be used.

クライアント・アプリケーションが接続を閉じると newLISP も終了します。
When the client application closes the connection, newLISP will exit, too.


TCP/IP daemon mode(TCP/IP デーモン モード)

-p モードでは、クライアントへの接続を閉じると newLISP は終了します。 これを避けるためには、-p の代わりに -d オプションを使ってください:
When the connection to the client is closed in -p mode, newLISP exits. To avoid this, use the -d option instead of the -p option:

newlisp -d 4711 &

これは -p オプションのように動作しますが、接続を閉じても newLISP は終了しません。 代わりにメモリにとどまり、新しい接続を待ち受け(listen)、その状態を維持します。 クライアント・アプリケーションから発行された exit がネットワーク接続を閉じても、 newLISP デーモンは常駐を維持し、新しい接続を待ちます。 4711 の代わりにどんなポート番号も使えます。
This works like the -p option, but newLISP does not exit after a connection closes. Instead, it stays in memory, listening for a new connection and preserving its state. An exit issued from a client application closes the network connection, and the newLISP daemon remains resident, waiting for a new connection. Any port number could be used in place of 4711.

各処理が終わって接続を閉じる度に、newLISP はリセット処理を行ない、スタックとシグナルを初期化し、コンテキストを MAIN に戻します。 サーバー状態である間維持されるのは、プログラムと変数シンボルの内容のみです。
After each transaction, when a connection closes, newLISP will go through a reset process, reinitialize stack and signals and go to the MAIN context. Only the contents of program and variable symbols will be preserved when running a stateful server.

-p または -d モードで走っている時、複数行の宣言文を囲むために開始タグ [cmd] と終了タグ [/cmd] を使う必要があります。 それらは各々個別の行に現れなければなりません(訳注:[cmd][/cmd] を単独行にするということ)。 これにより、制御しているアプリケーションから長いコードを転送することが可能になります。
When running in -p or -d mode, the opening and closing tags [cmd] and [/cmd] must be used to enclose multiline statements. They must each appear on separate lines. This makes it possible to transfer larger portions of code from controlling applications.

次なる -d モードは、クライアント側で net-eval を使う分散処理環境でよく使われます:
The following variant of the -d mode is frequently used in a distributed computing environment, together with net-eval on the client side:

newlisp -c -d 4711 &

-c を指定することで、プロンプト表示を抑制し、 関数 net-eval からの要求リクエストを受け取るのに適したモードにします。
The -c spec suppresses prompts, making this mode suitable for receiving requests from the net-eval function.

走っている newLISP サーバー・ノードは、 HTTPGETPUTDELETE 要求リクエストにも応えます。 get-urlput-urldelete-urlread-filewrite-fileappend-file を使ってのファイルの引き出しや保存ができ、 loadsave を使ってのリモート・サーバー・ノードへのプログラムのロードとセーブができます。 詳細は -c-http オプションの章を見てください。
newLISP server nodes running will also answer HTTP GET, PUT and DELETE requests. This can be used to retrieve and store files with get-url, put-url, delete-url, read-file, write-file and append-file, or to load and save programs using load and save from and to remote server nodes. See the chapters for the -c and -http options for more details.


HTTP-only server mode(HTTP のみのサーバー モード)

-http を使うことで、newLISP の処理を HTTP 処理に制限することができます。 このモードにより、セキュアな httpd ウェブ・サーバー・デーモンが構成されます:
newLISP can be limited to HTTP processing using the -http option. With this mode, a secure httpd web server daemon can be configured:

newlisp -http -d 8080 -w /usr/home/www

Unix 機において、newLISP を inetdxinetd が可能なサーバーとして走らせる時は、次のようにして使います:
When running newLISP as an inetd or xinetd-enabled server on Unix machines, use:

newlisp -http -w /usr/home/www

このモードを使って、よりセキュリティの高い HTTP 処理を行なうには、 スタートアップ時、次のようにプログラムをロードしてください:
To further enhance security and HTTP processing, load a program during startup when using this mode:

newlisp httpd-conf.lsp -http -w /usr/home/www

ファイル httpd-conf.lsp では、関数command-event に、要求リクエストの解析・フィルタ・翻訳用ユーザ定義関数を指定してあります。 動作例については、この関数(訳注:command-event)のリファレンスを見てください。
The file httpd-conf.lsp contains a command-event function configuring a user-defined function to analyze, filter and translate requests. See the reference for this function for a working example.

-c または -http どちらかの HTTP モードでも、次のファイル型が認識され、正しく整形された Content-Type: ヘッダーを返送します:
In the HTTP modes enabled by either -c or -http, the following file types are recognized, and a correctly formatted Content-Type: header is sent back:

file extensionmedia type
.avivideo/x-msvideo
.csstext/css
.gifimage/gif
.htmtext/htm
.htmltext/html
.jpgimage/jpg
.jsapplication/javascript
.movvideo/quicktime
.mp3audio/mpeg
.mpgvideo/mpeg
.pdfapplication/pdf
.pngimage/png
.wavaudio/x-wav
.zipapplication/zip
any othertext/plain

HTTP サーバー・モードは CGI を提供するために、 Unix ライク・プラットフォームでは /tmp ディレクトリを、 MS Windows では C:\tmp ディレクトリを必要とします。 newLISP は GET、PUT、POST、DELETE 要求リクエストを処理し、カスタムの応答レスポンスヘッダを生成します。 CGI ファイルは拡張子を .cgi にしておく必要があり、さらに UNIX では実行許可を持ってなければなりません。 newLISP サーバー・モード CGI 処理についての詳細情報は、Code Patterns in newLISP ドキュメントで見ることができます。
To serve CGI, HTTP server mode needs a /tmp directory on Unix-like platforms or a C:\tmp directory on MS Windows. newLISP can process GET, PUT, POST and DELETE requests and create custom response headers. CGI files must have the extension .cgi and have executable permission on Unix. More information about CGI processing for newLISP server modes can be found in the document Code Patterns in newLISP

-c-http の両サーバー・モードでは、環境変数 DOCUMENT_ROOT、REQUEST_METHOD、REQUEST_URI、SERVER_SOFTWARE、QUERY_STRING が設定されます。 クライアントから送られた HTTP ヘッダに存在するなら、変数 CONTENT_TYPE、CONTENT_LENGTH、HTTP_HOST、HTTP_USER_AGENT、HTTP_COOKIE も設定されます。 環境変数は関数 env を使って読むことができます。
In both server modes -c and -http the environment variables DOCUMENT_ROOT, HTTP_HOST, REMOTE_ADDR, REQUEST_METHOD, REQUEST_URI, SERVER_SOFTWARE and QUERY_STRING are set. The variables CONTENT_TYPE, CONTENT_LENGTH, HTTP_HOST, HTTP_USER_AGENT and HTTP_COOKIE are also set, if present in the HTTP header sent by the client. Environment variables can be read using the env function.


Local domain Unix socket server(ローカル ドメイン Unix ソケット サーバー)

-d または -p サーバー・モードでは、ポートの代わりにローカル・ドメイン Unix ソケット・パスを指定できます。
Instead of a port, a local domain Unix socket path can be specified in the -d or -p server modes.

newlisp -c -d /tmp/mysocket &

別の newLISP プロセスを使ってサーバーをテストします:
Test the server using another newLISP process:

newlisp -e '(net-eval "/tmp/mysocket" 0 "(symbols)")'

これで、組込シンボルの全リストが端末に出力されます。
A list of all built-in symbols will be printed to the terminal

このモードは net-connectnet-listennet-eval のローカル・デーモン・ソケット・モードと共に動作します。 net-acceptnet-receivenet-send を使って、 net-connectnet-listen で開くローカル・デーモン・ソケットを提供できます。 net-peeknet-select を使って、ローカル・デーモン・ソケット接続を監視できます。
This mode will work together with local domain socket modes of net-connect, net-listen, and net-eval. Local domain sockets opened with net-connect and net-listen can be served using net-accept, net-receive, and net-send. Local domain socket connections can be monitored using net-peek and net-select.

ローカル・デーモン・ソケット接続は通常の TCP/IP ネットワーク接続よりも高速で、同じローカルファイルシステム上でアプリケーションを配布するプロセス間通信に向いています。 このモードは、MS Windows では利用できません。
Local domain socket connections are much faster than normal TCP/IP network connections and preferred for communications between processes on the same local file system in distributed applications. This mode is not available on MS Windows.


Connection timeout(接続のタイムアウト)

-p または -d デーモン・モードで走っている時の接続タイムアウト時間を指定します。 newLISP サーバーはクライアント接続を受け入れ後、さらなる入力が無い時は接続を断ちます。 タイムアウト時間は μ秒で指定します:
Specifies a connection timeout when running in -p or -d demon mode. A newLISP Server will disconnect when no further input is read after accepting a client connection. The timeout is specified in micro seconds:

newlisp -c -t 3000000 -d 4711 &

この例は 3秒のタイムアウト時間を指定しています。
The example specifies a timeout of three seconds.


inetd daemon mode(inetd デーモン モード)

事実上、全ての Linux/Unix OS 上で走っている inetd サーバーは、newLISP のプロキシとして機能します。 サーバーは、TCP/IP または UDP 接続を受け入れ、要求リクエストを標準 I/O を通して newLISP に渡します。 inetd は各クライアント接続用に newLISP プロセスを開始します。 クライアントが接続を断つと、接続が閉じられ、newLISP プロセスも終了します。
The inetd server running on virtually all Linux/Unix OSes can function as a proxy for newLISP. The server accepts TCP/IP or UDP connections and passes on requests via standard I/O to newLISP. inetd starts a newLISP process for each client connection. When a client disconnects, the connection is closed and the newLISP process exits.

newLISP はメモリ使用量が少ない上に実行も早く、プログラムのロード時間も短いので、inetd と newLISP の組み合わせは複数の接続を効率良く処理します。 net-eval を使って動作させる時、このモードが好まれるのは、分散処理環境で複数の要求リクエストを効率良く処理するためです。
inetd and newLISP together can handle multiple connections efficiently because of newLISP's small memory footprint, fast executable, and short program load times. When working with net-eval, this mode is preferred for efficiently handling multiple requests in a distributed computing environment.

servicesinetd.conf の二つのファイルを設定しておかなけばなりません。 どちらも ASCII 編集が可能で、通常 /etc/services/etc/inetd.conf で見つかります。
Two files must be configured: services and inetd.conf. Both are ASCII-editable and can usually be found at /etc/services and /etc/inetd.conf.

次の行のどちらかを inetd.conf に置いてください:
Put one of the following lines into inetd.conf:

net-eval  stream  tcp  nowait  root  /usr/local/bin/newlisp -c
											 
# as an alternative, a program can also be preloaded
											 
net-eval  stream  tcp  nowait  root  /usr/local/bin/newlisp -c myprog.lsp

root の代わりに別のユーザとオプション・グループを指定できます。 詳細は、inetd の Unix man ページを見てください。
Instead of root, another user and optional group can be specified. For details, see the Unix man page for inetd.

ファイル services には次の行を置いてください:
The following line is put into the services file:

net-eval        4711/tcp     # newLISP net-eval requests

macOS と Unix システムによっては、inetd の代わりに xinetd を使うことができます。 /etc/xinetd.d/ ディレクトリに net-eval というファイル名で次の内容を保存します:
On macOS and some Unix systems, xinetd can be used instead of inetd. Save the following to a file named net-eval in the /etc/xinetd.d/ directory:

service net-eval
{
    socket_type = stream
    wait = no
    user = root
    server = /usr/local/bin/newlisp
    port = 4711
    server_args = -c
    only_from = localhost
}

セキュリティ上の理由から、root は別ユーザに変更すべきであり、 適切に調整された www ドキュメント・ディレクトリのファイル許可も同様です。 only_from 指定は、リモート・アクセスを許可するために取ることができます。
For security reasons, root should be changed to a different user and file permissions of the www document directory adjusted accordingly. The only_from spec can be left out to permit remote access.

他の構成オプションは xinetdxinetd.conf の man ページを見てください。
See the man pages for xinetd and xinetd.conf for other configuration options.

デーモンを設定した後、新規または変更した構成ファイルを読み込ませるために、inetd あるいは xinetd を(訳注:次のようにして)再起動する必要があります:
After configuring the daemon, inetd or xinetd must be restarted to allow the new or changed configuration files to be read:

kill -HUP <pid>

走っている xinetd プロセスのプロセスID で <pid> を置き換えてください。
Replace <pid> with the process ID of the running xinetd process.

4711 以外の数値や TCP 以外のネットワーク・プロトコルを指定することもできます。
A number or network protocol other than 4711 or TCP can be specified.

プロンプトなしの newLISP コマンドラインで入力されたかのように、 newLISP は全てを処理します。 inetd セットアップをテストするために telnetプログラムを使用できます:
newLISP handles everything as if the input were being entered on a newLISP command-line without a prompt. To test the inetd setup, the telnet program can be used:

telnet localhost 4711

これで newLISP 式が入力でき、inetd は自動的に newLISP プロセスのスタートアップ通信を処理します。 複数行の式は、[cmd][/cmd] のタグで囲むことで、 各々個別の行として入力できます。
newLISP expressions can now be entered, and inetd will automatically handle the startup and communications of a newLISP process. Multiline expressions can be entered by bracketing them with [cmd] and [/cmd] tags, each on separate lines.

newLISP サーバ・ノード は、HTTP GETPUT要求リクエストに返答します。 これは、 get-urlput-urlread-filewrite-fileappend-file によるファイルの取り出しや保存、および、 loadsave を使っての リモート・サーバ・ノードへのプログラムのロードとセーブを 可能にします。
newLISP server nodes answer HTTP GET and PUT requests. This can be used to retrieve and store files with get-url, put-url, read-file, write-file and append-file, or to load and save programs using load and save from and to remote server nodes.


Linking a source file with newLISP for a new executable(newLISP 新実行部とソースとの統合)

コマンド・ライン・フラグ -x を使い、ソース・コードと newLISP 実行部を一緒にして、自己完結アプリケーションを構築できます。
Source code and the newLISP executable can be linked together to build a self-contained application by using the -x command line flag.

;; uppercase.lsp - Link example
(println (upper-case (main-args 1)))
(exit)

プログラム uppercase.lsp はコマンド・ライン上の最初の単語を取り、それを大文字に変換します。
The program uppercase.lsp takes the first word on the command-line and converts it to uppercase.

次のようなステップで自己完結アプリケーションを構築します:
To build this program as a self-contained executable, follow these steps:

# on OSX, Linux and other UNIX

newlisp -x uppercase.lsp uppercase

chmod 755 uppercase # give executable permission

# on Windows the target needs .exe extension

newlisp -x uppercase.lsp uppercase.exe

newLISP は実行環境のパスで newLISP 実行部を探し、ソース・コードのコピーとリンクします。
newLISP will find a newLISP executable in the execution path of the environment and link a copy of the source code.

uppercase "convert me to uppercase"

Linux や 他の UNIX では、現ディレクトリが実行パスでない場合は:
On Linux and other UNIX, if the current directory is not in the executable path:

./uppercase "convert me to uppercase"

上記実行で、コンソールには次のような出力が現れます:
The console should print:

CONVERT ME TO UPPERCASE

リンクしたプログラムは、起動時に初期化ファイル init.lsp あるいは .init.lsp をロードしないので注意してください。
Note that neither one of the initialization files init.lsp nor .init.lsp is loaded during startup of linked programs.


§ )

5. Startup, directories, environment(スタートアップ、ディレクトリ、環境)

Environment variable NEWLISPDIR(環境変数 NEWLISPDIR)

newLISP は、スタートアップ時に環境変数 NEWLISPDIR が設定されていないなら、それを設定します。 Linux、BSDs、macOS 等のUnix 上では、その変数を /usr/local/share/newlisp に設定します。 MS Windows 上では、%PROGRAMFILES%/newlisp になります。 ほとんどの MS Windows システムの %PROGRAMFILES%C:\Program Files (x86)\ ディレクトリに設定されています。
During startup, newLISP sets the environment variable NEWLISPDIR, if it is not set already. On Linux, BSDs, macOS and other Unixes the variable is set to /usr/local/share/newlisp. On MS Windows the variable is set to %PROGRAMFILES%/newlisp. On most MS Windows systems %PROGRAMFILES% evaluates to the C:\Program Files (x86)\ directory.

環境変数 NEWLISPDIR が役立つのは、newLISP と一緒にインストールされるファイルを次のようにロードする時です:
The environment variable NEWLISPDIR is useful when loading files installed with newLISP:

(load (append (env "NEWLISPDIR") "/modules/mysql.lsp"))

関数 module を使えば、modules/ ディレクトリからロードする二番目の宣言文を短くできます:
A predefined function module can be used to shorten the second statement loading from the modules/ directory:

(module "mysql.lsp")

The initialization file init.lsp(初期化ファイル init.lsp

コマンドラインで指定されたファイルをロードする前、そして、バナーやプロンプトが示される前に、 newLISP はホーム・ディレクトリから .init.lsp のロードを試みます。 macOS、Linux、その他 Unix では、ホーム・ディレクトリは HOME 環境変数で見つかります。 MS Windows では、このディレクトリ名は環境変数 USERPROFILEDOCUMENT_ROOT に含まれています。
Before loading any files specified on the command-line, and before the banner and prompt are shown. newLISP tries to load a file .init.lsp from the home directory of the user starting newLISP. On macOS, Linux and other Unix the home directory is found in the HOME environment variable. On MS Windows the directory name is contained in the USERPROFILE or DOCUMENT_ROOT environment variable.

もし、ホーム・ディレクトリで .init.lsp を見つけられないなら、 newLISP は環境変数 NEWLISPDIR で見つかるディレクトリから init.lsp ファイルのロードを試みます。
If a .init.lsp cannot be found in the home directory newLISP tries to load the file init.lsp from the directory found in the environment variable NEWLISPDIR.

newLISP を共有ライブラリとして起動すると、環境変数 NEWLISPLIB_INIT にある初期化ファイルを探します。 初期化ファイルはフル・パス名で指定されていることが必要です。 NEWLISPLIB_INIT が定義されていなければ、このライブラリ・モジュールは初期化ファイルをロードしません。
When newLISP is run as a shared library, an initialization file is looked for in the environment variable NEWLISPLIB_INIT. The full path-name of the initialization file must be specified. If NEWLISPLIB_INIT is not defined, no initialization file will be loaded by the library module.

newLISP が走るために init.lsp は必要ありませんが、関数やシステム共通変数を定義するのに便利です。
Although newLISP does not require init.lsp to run, it is convenient for defining functions and system-wide variables.

リンク・プログラムのスタートアップ中は、初期化ファイル init.lsp または .init.lsp のどちらもロードされないので、注意してください。また、-n-h-x オプションの何れかでもロードされません。
Note that neither one of the initialization files init.lsp nor .init.lsp is loaded during startup of linked programs or when one of the options -n, -h, -x is specified.


Directories on Linux, BSD, macOS and other Unix (Linux, BSD, macOS の ディレクトリ)

/usr/local/share/newlisp/modules ディレクトリには、POP3 mail 等の有用な関数群のモジュールが入っています。 /usr/local/share/doc/newlisp/ ディレクトリには、HTML形式のドキュメントが入っています。
The directory /usr/local/share/newlisp/modules contains modules with useful functions POP3 mail, etc. The directory /usr/local/share/doc/newlisp/ contains documentation in HTML format.


Directories on MS Windows(MS Windows のディレクトリ)

MS Windows システムでは、全ファイルがデフォルトの %PROGRAMFILES%¥newlisp ディレクトリにインストールされます(訳注:インストール・プログラム実行時にインストール・ディレクトリを変更することもできます)。 PROGRAMFILES は MS Windows の環境変数で、日本語環境へのインストールでは結果として C:¥Program files¥newlisp¥ になります。 %PROGRAMFILES%¥newlisp¥modules サブ・ディレクトリには、外部ライブラリへのインタフェース用モジュールやサンプル・プログラムが入っています。
On MS Windows systems, all files are installed in the default directory %PROGRAMFILES%\newlisp. PROGRAMFILES is a MS Windows environment variable that resolves to C:\Program files\newlisp\ in English language installations. The subdirectory %PROGRAMFILES%\newlisp\modules contains modules for interfacing to external libraries and sample programs.



§ )

6. Extending newLISP with shared libraries(共有ライブラリによる newLISP の拡張)

Unix や MS Windows の多くの共有ライブラリは newLISP の機能を拡張するために使えます。 例えば、グラフィカル・ユーザ・インターフェイス用ライブラリや暗号・復号用ライブラリ、データベース・アクセス用などがあります。
Many shared libraries on Unix and MS Windows systems can be used to extend newLISP's functionality. Examples are libraries for writing graphical user interfaces, libraries for encryption or decryption and libraries for accessing databases.

外部ライブラリから関数を導入するには、関数import を使います。 外部ライブラリからのコールバック関数を登録するには、関数callback を使います。 導入したライブラリ関数への入出力用フォーマットを簡単に実現できる関数として、 packunpackget-charget-stringget-intget-long 等があります。 関数 cpymem は指定したアドレスを直接メモリーからメモリへコピーします。
The function import is used to import functions from external libraries. The function callback is used to register callback functions in external libraries. Other functions like pack, unpack, get-char, get-string, get-int and get-long exist to facilitate formatting input and output to and from imported library functions. The fucntion cpymem allows direct memory-to-memory copy specifying addresses.

共有ライブラリ用 API を書くときに使う関数のほとんどが、正しく使わないとセグメンテーション違反を起こします。 このマニュアルの にリンクした章に、そのような関数が記してあります。
。 Most of the functions used when writing APIs for share libraries can cause newLISP to segfault when not used correctly. The reference documentation marks these functions with a character linking to this chapter.

Code Patterns in newLISP 文書の 23. Extending newLISP の章も見てください。
See also the chapter 23. Extending newLISP in the Code Patterns in newLISP document.


§ )

7. newLISP as a shared library(共有ライブラリとしての newLISP)

newLISP as C library(C ライブラリとしての newLISP)

newLISP は共有ライブラリとしてもコンパイルできます。 Linux や BSD 等の Unix ではライブラリを newlisp.so から呼び出します。 Windows なら newlisp.dll、macOS では newlisp.dylib です。 newLISP 共有ライブラリは他の共有ライブラリと同じようにして使えます。 newLISP 共有ライブラリは他のプログラム言語に newLISP 機能を導入するために必要なものです。
newLISP can be compiled as a shared library. On Linux, BSDs and other Unix flavors the library is called newlisp.so. On Windows it is called newlisp.dll and newlisp.dylib on macOS. A newLISP shared library is used like any other shared library. A newLISP shared library is only required for importing newLISP functionality into other programming languages.

導入できる主な関数は newlispEvalStr です。 この関数は eval-string のように newLISP の式からなる文字列を取り、結果を文字列のアドレスに保存します。 結果は get-string を使って取り出せます。 結果の文字列はコマンド・ライン・セッションの出力のように整形されます。 ライン・フィード終端文字は含まれますが、プロンプト記号は含みません。
The main function to import is newlispEvalStr. Like eval-string, this function takes a string containing a newLISP expression and stores the result in a string address. The result can be retrieved using get-string. The returned string is formatted like output from a command-line session. It contains terminating line-feed characters, but not the prompt string.

関数 newlispEvalStr の呼び出しで、コンソールに向けられる出力(例えば、戻り値や print 文)は、通常文字列ポインタの整数値で返されます。 このポインタを関数 get-string に渡すことで、出力にアクセスできます。(訳注: get-string )戻り値の(訳注:コンソールへの)出力を止めるには silent 命令を使ってください。
When calling newlispEvalStr, output normally directed to the console (e.g. return values or print statements) is returned in the form of an integer string pointer. The output can be accessed by passing this pointer to the get-string function. To silence the output from return values, use the silent function.

コンソール上で stdio を使えるようにするには、newlispLibConsole を導入し、1 をパラメータにして呼び出します。そうすれば、コンソール上から stdinstdout に I/O できます。
To enable stdio on the console, import the function newlispLibConsole and call it with a parameter of 1 for enabling I/O on the console with stdin and stdout.

v.10.3.3 から newlispCallback を使って、コールバックを登録できるようになりました。 詳細は、Code Patterns in newLISP 文書の 24. newLISP compiled as a shared library の章を読んでください。
Since v.10.3.3 callbacks can also be registered using newlispCallback. For more information read the chapter 24. newLISP compiled as a shared library in the Code Patterns in newLISP document.

newLISP as a JavaScript library(JavaScript ライブラリとしての newLISP)

バージョン 10.5.7 から、newLISP は Emscripten ツールを使って、JavaScript にもコンパイルできます。 このライブラリを使えば、ウェブ・ブラウザのクライアント側で JavaScript や HTML のように newLISP を走らせることができます。 HTML ページには newLISP コードと JavaScript コードを混在でき、両言語間で互いに呼び出し合うことができます。 詳細情報は、配布パッケージ中の newlisp-js-x.x.x.zip を見てください。newlisp-js-lib.js ライブラリやドキュメント、例題アプリケーションが入っています。 ブラウザ・ベースの簡単な newLISP 開発環境がここからアクセスできます:newlisp-js。 このアプリケーションには、ほかの例題アプリケーションやドキュメントへのリンクが含まれています。 ダウンロード・リンクには、全パッケージがリンクされています。
Since version 10.5.7, newLISP can be compiled to JavaScript using the Emscripten toolset. The library can be used to run newLISP clientr-side in a web browser, just like JavaScript or HTML. An HTML page can host both, newLISP code and JavaScript code together. Both languages can call each other. For more information see the newlisp-js-x.x.x.zip distribution package which contains the library newlisp-js-lib.js, documentaion and example applications. A small newLISP development environment hosted in a browser can also be accessed here: newlisp-js The application contains links to another example application, documentation and a download link for the whole package.

JavaScript ライブラリとしてコンパイルされた newLISP には、ウェブ・ブラウザ用 newLISP の API の新関数がつかされています。
newLISP compiled as a JavaScript library adds new functions linked from API for newLISP in a web browser.


§ )

8. Evaluating newLISP expressions(newLISP 式の評価)

この章は、newLISP 宣言文の評価と newLISP における整数と浮動小数点数の規則に関する短い紹介です。
The following is a short introduction to newLISP statement evaluation and the role of integer and floating point arithmetic in newLISP.

load 関数を使った時、もしくは、コマンド・ライン上のコンソールで式を入力した時、トップ・レベルの式が評価されます。
Top-level expressions are evaluated when using the load function or when entering expressions in console mode on the command-line.


Interactive Multiline expressions(インターラクティブ時の複数行の式)

最初に空行を入力することで、複数行の式を入力できます。 一旦、複数行モードに入り、再び入力モードに戻るには、空行を入力します。 そうすると、入力して宣言文一式が評価されます(出力は太字):
Multiline expressions can be entered by entering an empty line first. Once in multiline mode, another empty line returns from entry mode and evaluates the statement(s) entered (ouput in boldface):

>
(define (foo x y)
    (+ x y))

(lambda (x y) (+ x y))
> (foo 3 4)
7
> _

空行で enter キーを打って複数行モードに入ると、プロンプト表示が抑制されます。 もう一度空行を入力することで複数行モードから離れ、式が評価されます。
Entering multiline mode by hitting the enter key on an empty line suppresses the prompt. Entering another empty line will leave the multiline mode and evaluate expressions.

空行入力の代わりに、[cmd][/cmd] のタグも使え、 その際、各々別の行として入力します。 このモードは、いくつかの newLISP 制御インターラクティブ IDE でも使われますし、関数net-eval でも内部的に使われます。
As an alternativo to entering empty lines, the [cmd] and [/cmd] tags are used, each entered on separate lines. This mode is used by some interactive IDEs controlling newLISP and internally by the net-eval function.


Integer, floating point data and operators(整数、浮動小数点データと演算子)

newLISP の関数や演算子は、整数と浮動小数点数を受け入れ、 必要な形式に変換します。 例えば、ビット操作演算子は浮動小数点数の小数部分を省いて整数に変換します。 同様に、三角関数は計算を実行する前、内部的に整数を浮動小数点数に変換しています。
newLISP functions and operators accept integer and floating point numbers, converting them into the needed format. For example, a bit-manipulating operator converts a floating point number into an integer by omitting the fractional part. In the same fashion, a trigonometric function will internally convert an integer into a floating point number before performing its calculation.

シンボル演算子 (+ - * / % $ ~ | ^ << >>) は整数型の値を返します。 シンボルの代わりに単語としての名前を持つ関数や演算子(例えば、+ の代わりに add )は浮動小数点数を返します。 整数演算子は浮動小数点数の小数を切り捨て、整数にします。
The symbol operators (+ - * / % $ ~ | ^ << >>) return values of type integer. Functions and operators named with a word instead of a symbol (e.g., add rather than +) return floating point numbers. Integer operators truncate floating point numbers to integers, discarding the fractional parts.

newLISP は、基本的な算術演算子として二つのタイプを持っています: 整数 (+ - * /) 用と 浮動小数点 (add sub mul div)用です。 算術関数は関数自身の型と互換性のある型に引数を変換します:整数関数は引数を整数に、浮動小数点関数は引数を浮動小数点に。 newLISP を他のスクリプト言語のように動作させるために、 整数演算子 +, -, *, / で 浮動小数点演算 add, sub, mul, div を 実行するよう再定義できます:
newLISP has two types of basic arithmetic operators: integer (+ - * /) and floating point (add sub mul div). The arithmetic functions convert their arguments into types compatible with the function's own type: integer function arguments into integers, floating point function arguments into floating points. To make newLISP behave more like other scripting languages, the integer operators +, -, *, and / can be redefined to perform the floating point operators add, sub, mul, and div:

(constant '+ add)
(constant '- sub)
(constant '* mul)
(constant '/ div)
 
;; or all 4 operators at once
(constant '+ add '- sub '* mul '/ div)

これで共通算術演算子 +, -, *, / は、整数と浮動小数点数を受け入れ、浮動小数点の結果を返します。
Now the common arithmetic operators +, -, *, and / accept both integer and floating point numbers and return floating point results.

この場合、導入したライブラリから整数を想定している関数を使う時は、注意を払わなければなりません。 +, -, *, / を再定義した後では、整数の代わりに倍精度浮動小数点数を不用意に渡すことになるかもしれません。 このような時は、関数 int を使って、浮動小数点数を整数に変換できます。 同様に、float 関数を使って、整数を浮動小数点数に変換することもできます:
Care must be taken when importing from libraries that use functions expecting integers. After redefining +, -, *, and /, a double floating point number may be unintentionally passed to an imported function instead of an integer. In this case, floating point numbers can be converted into integers by using the function int. Likewise, integers can be transformed into floating point numbers using the float function:

(import "mylib.dll" "foo")  ; importing int foo(int x) from C
(foo (int x))               ; passed argument as integer
(import "mylib.dll" "bar")  ; importing C int bar(double y)
(bar (float y))             ; force double float

newLISP に搭載されているモジュールには、 +, -, *, / のデフォルトの実装を想定して書かれているものがあります。 これは、導入されるライブラリ関数のアドレス計算実行時に、最大スピードを与えるためです。
Some of the modules shipping with newLISP are written assuming the default implementations of +, -, *, and /. This gives imported library functions maximum speed when performing address calculations.

newLISP 好きなら、 整数演算子として定義された +, -, *, / をそのままにして、 明らかに要求された時のみ、add, sub, mul, div を使うでしょう。 バージョン 8.9.7 から、newLISP の整数演算は 64 ビット演算ですが、64 ビット倍精度浮動小数点数が提供する整数部の精度は 52 ビットです。
The newLISP preference is to leave +, -, *, and / defined as integer operators and use add, sub, mul, and div when explicitly required. Since version 8.9.7, integer operations in newLISP are 64 bit operations, whereas 64 bit double floating point numbers offer only 52 bits of resolution in the integer part of the number.


Big integer, multiple precision arithmetic(算術精度に制限のない大整数)

次の演算子、関数、述語が大整数に対して動作します:
The following operators, functions and predicates work on big integers:

functiondescription
+ - * / ++ -- % 算術演算子
arithmetic operators
< > = <= >= != 論理演算子
logical operators
abs 数値の絶対値を返す
returns the absolute value of a number
gcd 最大公約数を計算する
calculates the greatest common divisor of a group of integers
even? 整数の偶奇をチェック
checks the parity of an integer number
odd? 整数の奇数をチェック
checks the parity of an integer number
number? 数値のチェック
checks if an expression is a float or an integer
zero? ゼロのチェック
checks if an expression is 0 or 0.0

これらの演算子や関数の引数の一番目が大整数なら、大整数モードで計算を実行します。このマニュアルの関数リファレンス節では、これらの関数に bigint が記されています。
If the first argument in any of these operators and functions is a big integer, the calculation performed will be in big integer mode. In the Function Reference section of this manual these are marked with a bigint suffix.

文字通り、9223372036854775807 より大きい数や -9223372036854775808 より小さい数、または末尾に L のつく数は、大整数に変化され、そのモードで処理されます。 整数や浮動小数点や文字列形式からの変換には、関数 bigint が使えます。 bigint? 述語は大変数型かどうかをチェックします。
Literal integer values greater than 9223372036854775807 or smaller than -9223372036854775808, or integers with an appended letter L, will be converted and processed in big integer mode. The function bigint can be used to convert from integer, float or string format to big integer. The predicate bigint? checks for big integer type.

; first argument triggers big integer mode because it's big enough

(+ 123456789012345678901234567890 12345)  123456789012345678901234580235L

; first small literal put in big integer format by 
; appending L to guarantee big integer mode

(+ 12345L 123456789012345678901234567890)  123456789012345678901234580235L

(setq x 1234567890123456789012345)
(* x x)  1524157875323883675049533479957338669120562399025L

; conversion from bigint to float introduces rounding errors

(bigint (float (* x x)))  1524157875323883725344000000000000000000000000000L


; sequence itself does not take big integers, before using
; apply, the sequence is converted with bigint

(apply * (map bigint (sequence 1 100))) ; calculate 100!
 93326215443944152681699238856266700490715968264381
  62146859296389521759999322991560894146397615651828
  62536979208272237582511852109168640000000000000000
  00000000L

; only the first operand needs to be bigint for apply
; to work. The following gives the same result

(apply * (cons 1L (sequence 2 100)))

; length on big integers returns the number of decimal digits
(length (apply * (map bigint (sequence 1 100)))) 
 158 ; decimal digits

; all fibonacci numbers up to 200, only the first number 
; needs to be formatted as big integer, the rest follows
; automatically - when executed from the command line in 
; a 120 char wide terminal, this shows a beautiful pattern

(let (x 1L) (series x (fn (y) (+ x (swap y x))) 200))

整数と大整数が混在する算術計算では、演算誤差を避けるために第一引数を大整数にすべきです。
When doing mixed integer / big integer arithmetic, the first argument should be a big integer to avoid erratic behaviour.

; because the first argument is 64-bit, no big integer arithmetic 
; will be done, although the second argument is big integer 

(+ 123 12345L)
 12468

; the second argument is recognized as a big integer
; and overflows the capacity of a 64-bit integer

(+ 123 123453456735645634565463563546)
 ERR: number overflows in function +

; now the first argument converts to big integer and the
; whole expression is evaluates in big integer mode

(+ 123L 123453456735645634565463563546)
 123453456735645634565463563669L

浮動小数点が混在するほとんどの場合、整数と大整数に違いはありません。 第二引数に必要な変換を関数が自動的に行います。 通常の整数や浮動小数点のみを使う場合のオーバーフローは、バージョン 10.5.0 以前の newLISP と変わっていません。
Under most circumstances mixing float, integers and big integers is transparent. Functions automatically do conversions when needed on the second argument. The overflow behavior when using normal integers and floats only, has not changed from newLISP versions previous to 10.5.0.


Evaluation rules and data types(評価ルールとデータ型)

コマンドラインで入力または編集された式を評価します。 複雑なプログラムは Emacs や VI のようなエディタを使って入力できます。 それらのエディタはタイプ中に対応する括弧を示すモードを持っています。 load 関数を使って、コンソール・セクションに保存したファイルを呼び戻せます
Evaluate expressions by entering and editing them on the command-line. More complicated programs can be entered using editors like Emacs and VI, which have modes to show matching parentheses while typing. Load a saved file back into a console session by using the load function.

一行コメントは、;(セミコロン)か #番号記号)で始まり、行の終わりまで及びます。 Linux/Unix 環境でスクリプト言語として newLISP を使う時は # が便利です。 Linux/Unix ではスクリプトとシェルの一行コメントして # が共通に使えるからです。
A line comment begins with a ; (semicolon) or a # (number sign) and extends to the end of the line. newLISP ignores this line during evaluation. The # is useful when using newLISP as a scripting language in Linux/Unix environments, where the # is commonly used as a line comment in scripts and shells.

コマンドラインで評価が起こると、結果はコンソール・ウィンドウに出力されます。
When evaluation occurs from the command-line, the result is printed to the console window.

続く例題は → シンボルの左側のコードをタイプしてコマンドラインに入力します。 次の行に現れる結果は → シンボルの右側のコードと一致するはずです。
The following examples can be entered on the command-line by typing the code to the left of the    symbol. The result that appears on the next line should match the code to the right of the    symbol.

niltrue は、それ自身に評価される論理データ型です:
nil and true are Boolean data types that evaluate to themselves:

nil     nil
true    true

整数大整数浮動小数点 の数値は、それ自身に評価されます:
Integers, big integers and floating point numbers evaluate to themselves:

123       123    ; decimal integer
0xE8      232    ; hexadecimal prefixed by 0x
055       45     ; octal prefixed by 0 (zero)
0b101010  42     ; binary prefixed by 0b
1.23      1.23   ; float
123e-3    0.123  ; float in scientific notation

123456789012345678901234567890
 123456789012345678901234567890L ; parses to big integer

整数は符号ビットを含む 64 ビット数値です。 有効整数は -9,223,372,036,854,775,808 と +9,223,372,036,854,775,807 の間です。 浮動小数点数から変換される最大数は、二つの制限の内の一つに丸められます。 newLISP の内部整数で 32 ビット数値で制限されるもの(訳注:例えば、date-parse)は、+2,147,483,647 か -2,147,483,648 のどちらかでオーバーフローします。
Integers are 64-bit numbers including the sign bit. Valid integers are numbers between -9,223,372,036,854,775,808 and +9,223,372,036,854,775,807. Larger numbers converted from floating point numbers are truncated to one of the two limits. Integers internal to newLISP, which are limited to 32-bit numbers, overflow to either +2,147,483,647 or -2,147,483,648.

浮動小数点数は IEEE 754 の 64 ビット倍精度です。 formatで特殊フォーマット文字を使えば、符号無しで 18,446,744,073,709,551,615 まで、表示可能です。
Floating point numbers are IEEE 754 64-bit doubles. Unsigned numbers up to 18,446,744,073,709,551,615 can be displayed using special formatting characters for format.

大整数はメモリが許す限り、桁数に制限がありません。 大整数に必要なメモリは:
Big integers are of unlimited precision and only limited in size by memory. The memory requirement of a big integer is:

bytes = 4 * ceil(digits / 9) + 4.

ここで digits は十進数桁数、bytes は 8 ビット、ceilは次に大きい整数に丸める切り上げ関数です。
Where digits are decimal digits, bytes are 8 bits and ceil is the ceiling function rounding up to the next integer.

文字列 は null 文字も含めることができ、異なる終端を持つことが可能です。 文字列もそれ自身に評価されます。
Strings may contain null characters and can have different delimiters. They evaluate to themselves.

"hello"             "hello"  
"\032\032\065\032"  "  A " 
"\x20\x20\x41\x20"  "  A "
"\t\r\n"            "\t\r\n" 
"\x09\x0d\x0a"      "\t\r\n"

;; null characters are legal in strings:
"\000\001\002"        "\000\001\002"
{this "is" a string}  "this \"is\" a string"
 
;; use [text] tags for text longer than 2047 bytes:
[text]this is a string, too[/text]
 "this is a string, too"

" (ダブル・クォート) で囲まれた文字列の中では、次の文字が \ (バックスラッシュ、訳注:日本語環境では '¥' ) でエスケープ処理されます:
Strings delimited by " (double quotes) will also process the following characters escaped with a \ (backslash):

characterdescription
\" ダブル・クォートで囲まれた文字列内のダブル・クォート
for a double quote inside a quoted string
\n ライン・フィード文字 (ASCII 10)
for a line-feed character (ASCII 10)
\r キャリッジ・リターン文字 (ASCII 13)
for a return character (ASCII 13)
\b バックスペース文字 (ASCII 8)
for a backspace BS character (ASCII 8)
\t タブ文字 (ASCII 9)
for a TAB character (ASCII 9)
\f フォームフィード文字 (ASCII 12)
for a formfeed FF character (ASCII 12)
\nnn 3桁の10進数によるアスキーコード数(000 から 255 までの nnn)
for a three-digit ASCII number (nnn format between 000 and 255)
\xnn 2桁の16進数によるアスキーコード数(x00 から xff までの xnn)
for a two-digit-hex ASCII number (xnn format between x00 and xff)
\unnnn 4桁の16進数による nnnn で表すユニコード文字。UTF8版の newLISP は、これを UTF8文字に変換します。
for a unicode character encoded in the four nnnn hexadecimal digits. newLISP will translate this to a UTF8 character in the UTF8 enabled versions of newLISP.
\\バックスラッシュ文字 (ASCII 92) 自体(訳注:日本語環境では '¥' )
for the backslash character (ASCII 92) itself

クォートの付いた文字列は 2,047 文字数を超えることはできません。 それより長い文字列は [text][/text] のタグの境界に使います。 newLISP では 2,047 文字を超える文字列出力に、このタグを自動的に使います。
Quoted strings cannot exceed 2,047 characters. Longer strings should use the [text] and [/text] tag delimiters. newLISP automatically uses these tags for string output longer than 2,047 characters.

{(左波括弧), }(右波括弧)と [text], [/text] の中ではエスケープ文字処理は行われません。
The { (left curly bracket), } (right curly bracket), and [text], [/text] delimiters do not perform escape character processing.

ラムダとラムダ・マクロ式 は、それ自身に評価されます:
Lambda and lambda-macro expressions evaluate to themselves:

(lambda (x) (* x x))                    (lambda (x) (* x x))
(lambda-macro (a b) (set (eval a) b))   (lambda-macro (a b) (set (eval a) b))
(fn (x) (* x x))                        (lambda (x) (* x x))  ; an alternative syntax

シンボル は、その内容に評価されます:
Symbols evaluate to their contents:

(set 'something 123)   123
something              123

コンテキスト は、それ自身に評価されます:
Contexts evaluate to themselves:

(context 'CTX)   CTX
CTX              CTX

組込関数 も、それ自身に評価されます:
Built-in functions also evaluate to themselves:

add                 add <B845770D>
(eval (eval add))   add <B845770D>
(constant '+ add)   add <B845770D>
+                   add <B845770D>

上記例で、< >(山括弧)間の数字は、関数add の16進数メモリ・アドレス(マシン依存)です。 組込プリミティブを表示する時、現れます。
In the above example, the number between the < > (angle brackets) is the hexadecimal memory address (machine-dependent) of the add function. It is displayed when printing a built-in primitive.

クォート式 は評価されると、一個の '(シングル・クォート)を失います:
Quoted expressions lose one ' (single quote) when evaluated:

'something   something
''''any      '''any
'(a b c d)   (a b c d)

シングル・クォートは、しばしば式を評価から保護 するのに使われます。 (例えば、シンボル自身をその内容に代わりに参照したい時や、データを表現するリストを参照したい時)。
A single quote is often used to protect an expression from evaluation (e.g., when referring to the symbol itself instead of its contents or to a list representing data instead of a function).

リスト は(Scheme と同様に)リストの第一要素が評価されてから、式の残りが評価されます。 第一要素の評価結果がリストの残りの要素に適用されますので、第一要素は lambda 式、lambda-macro 式、primitive(組込)関数のどれかでなければなりません。
Lists are evaluated by first evaluating the first list element before the rest of the expression (as in Scheme). The result of the evaluation is applied to the remaining elements in the list and must be one of the following: a lambda expression, lambda-macro expression, or primitive (built-in) function.

(+ 1 2 3 4)                   10
(define (double x) (+ x x))   (lambda (x) (+ x x))

または
or

(set 'double (lambda (x) (+ x x)))
(double 20)                40
((lambda (x) (* x x)) 5)   25

newLISP はユーザ定義ラムダ式において、引数を左から右へと評価して、パラメータに(左から右へ)束縛して、その結果を式本体で使います。
For a user-defined lambda expression, newLISP evaluates the arguments from left to right and binds the results to the parameters (also from left to right), before using the results in the body of the expression.

Scheme のように newLISP は式のファンクタ(関数オブジェクト)部分を評価して、その引数に適用します:
Like Scheme, newLISP evaluates the functor (function object) part of an expression before applying the result to its arguments. For example:

((if (> X 10) * +) X Y)

この式では、X の値次第で *(積)か +(和)を X と Y に適用しています。
Depending on the value of X, this expression applies the * (product) or + (sum) function to X and Y.

lambda-macro 式は引数を評価しないので、言語の構文を拡張する使えます。。 ほとんどの組込関数は実行時に(必要な時)引数を左から右へ評価します。 この規則の例外については、このマニュアルのリファレンス部分に示してあります。 引数の全てか一部を評価しない Lisp 関数は特殊形式 と呼ばれます。
Because their arguments are not evaluated, lambda-macro expressions are useful for extending the syntax of the language. Most built-in functions evaluate their arguments from left to right (as needed) when executed. Some exceptions to this rule are indicated in the reference section of this manual. Lisp functions that do not evaluate all or some of their arguments are called special forms.

アレイ は、それ自身に評価されます:
Arrays evaluate to themselves:

(set 'A (array 2 2 '(1 2 3 4)))  ((1 2) (3 4))
(eval A)                         ((1 2) (3 4))

シェル・コマンド:コマンドライン上で第一文字が !(感嘆符)で、 その後にシェル・コマンドが続いているなら、そのコマンドが実行されます。 例えば、Unix の !ls や MS Windows の !dir は、現在の作業ディレクトリの(訳注:ファイルの)リストを表示させます。 ! とシェル・コマンドの間にスペースは必要ありません。 ! で始まるシンボルは内部式として許容され、コマンドライン上ではスペースを先行することでシンボルとして認識されます。 注記:このモードはシェル上で走っている時のみ動作し、他のアプリケーションから newLISP を制御している時は動作しません。
Shell commands: If an ! (exclamation mark) is entered as the first character on the command-line followed by a shell command, the command will be executed. For example, !ls on Unix or !dir on MS Windows will display a listing of the present working directory. No spaces are permitted between the ! and the shell command. Symbols beginning with an ! are still allowed inside expressions or on the command-line when preceded by a space. Note: This mode only works when running in the shell and does not work when controlling newLISP from another application.

(訳例:
> (setq !a 1)
1
> !a
'a' は、内部コマンドまたは外部コマンド、
操作可能なプログラムまたはバッチ ファイルとして認識されていません。
> (eval !a)
1
>  !a
1
> 

newLISP シェルから出るには、Linux/Unix では Ctrl-D を押し、MS Windows 上では (exit) とタイプするか Ctrl-C です。
To exit the newLISP shell on Linux/Unix, press Ctrl-D; on MS Windows, type (exit) or Ctrl-C, then the x key.

他のアプリケーションでシェル・コマンドにアクセスする時や newLISP に結果を渡したい時は、関数 exec を使ってください。
Use the exec function to access shell commands from other applications or to pass results back to newLISP.


§ )

9. Lambda expressions in newLISP(newLISP におけるラムダ式)

newLISP におけるラムダ式は、それ自身に評価され、正規のリストと同様に扱われます:
Lambda expressions in newLISP evaluate to themselves and can be treated just like regular lists:

(set 'double (lambda (x) (+ x x)))
(set 'double (fn (x) (+ x x)))      ; alternative syntax

(last double)   (+ x x)            ; treat lambda as a list

注記:newLISP では、ラムダ式の前に ' は必要ありません。ラムダ式が、それ自身に評価されるからです。
Note: No ' is necessary before the lambda expression because lambda expressions evaluate to themselves in newLISP.

(訳注:上記例の)二行目では、Paul Graham が Arc 言語プロジェクトで提案している代替構文 fn キーワードを使っています。
The second line uses the keyword fn, an alternative syntax first suggested by Paul Graham for his Arc language project.

ラムダ式はラムダ・リスト というリスト の一形態であり、その引数は左から右、あるいは、右から左へと連結可能です。 例えば、append を使うと、左の引数が右に引数とつながります:
A lambda expression is a lambda list, a subtype of list, and its arguments can associate from left to right or right to left. When using append, for example, the arguments associate from left to right:

(append (lambda (x)) '((+ x x)))   (lambda (x) (+ x x))

一方、cons は右の引数(訳注:の先頭)に左の引数を入れます:
cons, on the other hand, associates the arguments from right to left:

(cons '(x) (lambda (+ x x)))   (lambda (x) (+ x x))

lambda キーワードはリスト中のシンボルではなく、ラムダ・リスト というリストの特殊 の指定子であることに注意してください。
Note that the lambda keyword is not a symbol in a list, but a designator of a special type of list: the lambda list.

(length (lambda (x) (+ x x)))   2
(first (lambda (x) (+ x x)))    (x)

ラムダ式はユーザ定義の無名関数として、map または apply の引数にすることができます:
Lambda expressions can be mapped or applied onto arguments to work as user-defined, anonymous functions:

((lambda (x) (+ x x)) 123)            246
(apply (lambda (x) (+ x x)) '(123))   246
(map (lambda (x) (+ x x)) '(1 2 3))   (2 4 6)

一ラムダ式を一シンボルに割り付け、関数として使うことができます:
A lambda expression can be assigned to a symbol, which in turn can be used as a function:

(set 'double (lambda (x) (+ x x)))   (lambda (x) (+ x x))
(double 123)                         246

関数 define はラムダ式をシンボルに割り付ける簡単な方法です:
The define function is just a shorter way of assigning a lambda expression to a symbol:

(define (double x) (+ x x)))   (lambda (x) (+ x x))
(double 123)                   246

上の例で、ラムダ・リスト内の式は double の中身としてアクセス可能です:
In the above example, the expressions inside the lambda list are still accessible within double:

(set 'double (lambda (x) (+ x x)))   (lambda (x) (+ x x))
(last double)                        (+ x x)

リストを操作する関数を使かえば、ラムダ・リストをファースト・クラス・オブジェクトのように操作できます:
A lambda list can be manipulated as a first-class object using any function that operates on lists:

(setf (nth 1 double) '(mul 2 x))      (lambda (x) (mul 2 x))
double                            (lambda (x) (mul 2 x))
(double 123)                      246

ラムダ式に与えられる引数は全てオプションであり、ユーザの指定がない時はデフォルトで nil が割り当てられます。 これにより、多様な変数を定義する関数を書くことが可能になります。
All arguments are optional when applying lambda expressions and default to nil when not supplied by the user. This makes it possible to write functions with multiple parameter signatures.


§ )

10. nil, true, cons, and ()(newLISP の niltruecons()

newLISP において niltrue は共にシンボルで、論理値の偽(false) 真(true)を表します。 niltrue 内容によっては異なる扱いを受けます。 次からの例は nil を使いますが、単に論理を逆にすることによって true にも適用できます。
In newLISP, nil and true represent both the symbols and the Boolean values false and true. Depending on their context, nil and true are treated differently. The following examples use nil, but they can be applied to true by simply reversing the logic.

nil の評価は論理値の偽をもたらし、if, unless, while, until, not のようなフロー制御式内部で偽として取り扱われます。 同様に true の評価は真をもたらします。
Evaluation of nil yields a Boolean false and is treated as such inside flow control expressions such as if, unless, while, until, and not. Likewise, evaluating true yields true.

(set 'lst '(nil nil nil))   (nil nil nil)
(map symbol? lst)           (true true true)

上の例では nil はシンボルです。 次の例では niltrue が評価され、論理値になります:
In the above example, nil represents a symbol. In the following example, nil and true are evaluated and represent Boolean values:

(if nil "no" "yes")   "yes"
(if true "yes" "no")  "yes"
(map not lst)         (true true true)

newLISP では他の Lisp と違って、nil と空リスト () が同じではありません。 両者が論理値の偽として扱われるのは、and, or, if, while, unless, until, cond の条件式においてのみです。
In newLISP, nil and the empty list () are not the same as in some other Lisps. Only in conditional expressions are they treated as a Boolean false, as in and, or, if, while, unless, until, and cond.

nil は空リストではなく、論理値として扱われるので、(cons 'x '()) の評価は (x) となりますが、(cons 'x nil)(x nil) になります。 newLISP では、二つのアトムのコンス(cons)はドット対にならず、二つの要素のリストになります。 述語 atom?nil に対して 真(true)ですが、空リストに対しては 偽(false)です。 newLISP では、空リストは単なる空のリストであり、nil ではありません。
Evaluation of (cons 'x '()) yields (x), but (cons 'x nil) yields (x nil) because nil is treated as a Boolean value when evaluated, not as an empty list. The cons of two atoms in newLISP does not yield a dotted pair, but rather a two-element list. The predicate atom? is true for nil, but false for the empty list. The empty list in newLISP is only an empty list and not equal to nil.

newLISP で一つのリストは、リストの形をした一 newLISP セルです。 それはリストセルの中身を形作る要素を連結するリストの入れ物のようなものです。 newLISP にドット対 はありません。 なぜなら、Lisp セルの cdr(tail)部が常に他の Lisp セルを指し示し、けして、数値やシンボルのような基本データ型を指し示さないからです。 car(head)部のみが基本データ型になりえます。 初期の Lisp 実装では、headtail の名前として carcdr を使っていました。
A list in newLISP is a newLISP cell of type list. It acts like a container for the linked list of elements making up the list cell's contents. There is no dotted pair in newLISP because the cdr (tail) part of a Lisp cell always points to another Lisp cell and never to a basic data type, such as a number or a symbol. Only the car (head) part may contain a basic data type. Early Lisp implementations used car and cdr for the names head and tail.


§ )

11. Arrays(アレイ)

newLISP のアレイは大規模リストの高速アクセスを可能にします。 関数 array を使って、新規アレイを構築し、既存リストの内容で初期化します。 リストをアレイに変換することもでき、その逆もできます。 リストの変更やアクセスに使用する関数のほとんどが、アレイにも同じように適用できます。 アレイにはどのようなデータ型も収めることができ、その組み合わせもしかりです。
newLISP's arrays enable fast element access within large lists. New arrays can be constructed and initialized with the contents of an existing list using the function array. Lists can be converted into arrays, and vice versa. Most of the same functions used for modifying and accessing lists can be applied to arrays, as well. Arrays can hold any type of data or combination thereof.

アレイの生成・アクセス・変更に、特に使われるのが次の関数群です:
In particular, the following functions can be used for creating, accessing, and modifying arrays:

functiondescription
append アレイを結合する
appends arrays
apply 関数や演算子を引数のリストに適用する
apply a function or operator to a list of arguments.
array 16次元までのアレイを作成し、初期化する
creates and initializes an array with up to 16 dimensions
array-list アレイをリストに変換する
converts an array into a list
array? アレイかどうかをチェックする
checks if expression is an array
corr 積率相関 係数を計算する
calculates the product-moment correlation coefficient
det 行列式を返す
returns the determinant of a matrix
dolist アレイの各要素で一回ずつ評価する
evaluates once for each element in an array vector
first アレイの第1要素を返す
returns the first row of an array
invert 逆行列を返す
returns the inversion of a matrix
last アレイの最後の要素を返す
returns the last row of an array
map 引数のベクターに関数を適用し、その結果を返す
applies a function to vector(s) of arguments and returns results in a list.
mat 行列のスカラー演算を実行する
perform scalar operations on matrices
multiply 行列の積をとる
multiplies two matrices
nth アレイの要素を返す
returns an element of and array
rest アレイの第一要素以外を返す
returns all but the first row of an array
reverse アレイの要素や行を逆にする
reverses the elements or rows in an array
setf 参照アレイの内容を設定する
sets contents of an array reference
slice アレイの一部を返す
returns a slice of an array
sort アレイの要素を並べ替える
sort the elements in an array
stats データ・ベクターの基本的統計値を計算する
calculates some basic statistics for a data vector
t-test スチューデントのt 統計値を使って、データ・サンプルの平均を比較する
compares means of data samples using the Student's t statistic
transpose 行列を置換する
transposes a matrix

newLISP はアレイをアレイ化して、多次元アレイを表します (すなわち、アレイの要素が、アレイ自身ということ)。
newLISP represents multidimensional arrays with an array of arrays (i.e., the elements of the array are themselves arrays).

インターラクティブに使われている時、newLISP はアレイをリストのように出力・表示するので、それらを区別できません。
When used interactively, newLISP prints and displays arrays as lists, with no way of distinguishing between them.

アレイ(または、アレイを含む変数)を直列化シリアライズするには、関数 sourcesave を使ってください。 そうすれば、アレイの直列化シリアライズ時に array 宣言文が定義部分に含まれます。
Use the source or save functions to serialize arrays (or the variables containing them). The array statement is included as part of the definition when serializing arrays.

リストと同様に、アレイの最後の要素から数え始める負数インデックスが使えます。
Like lists, negative indices can be used to enumerate the elements of an array, starting from the last element.

アレイまたはリストでインデックスが境界を超えると、エラー・メッセージが発生します。
An out-of-bounds index will cause an error message on an array or list.

正方でないアレイを作ることはできますが、sourcesave を使って直列化シリアライズする際に正方化されます。 関数array が、常に正方形式アレイを構築するからです。
Arrays can be non-rectangular, but they are made rectangular during serialization when using source or save. The array function always constructs arrays in rectangular form.

行列関数 det, transpose, multiply, invert は、 入れ子リストで構築された行列や array で構築されたアレイで使うことができます。
The matrix functions det, transpose, multiply, and invert can be used on matrices built with nested lists or arrays built with array.

詳細は、このマニュアルの array, array?, array-list のリファレンスで見てください。
For more details, see array, array?, and array-list in the reference section of this manual.


§ )

12. Indexing elements of strings, lists, and arrays(文字列、リスト、アレイの要素指定)

アレイ・リスト・文字列(複数の文字)の要素を一個以上の int-index (整数インデックス) で指定して、取り出す関数があります。 リストの要素数が N 個なら、正のインデックスの候補は 0, 1, …, N-2, N-1 です。 int-index が負なら、-N, -N+1, …, -2, -1 となります。 負のインデックスに N を足すと、正のインデックスになります。 関数で対応していなければ、N-1 を超えるインデックスや -N より小さいインデックスは、リストやアレイの境界外エラーを起こします。
Some functions take array, list, or string elements (characters) specified by one or more int-index (integer index). The positive indices run 0, 1, …, N-2, N-1, where N is the number of elements in the list. If int-index is negative, the sequence is -N, -N+1, …, -2, -1. Adding N to the negative index of an element yields the positive index. Unless a function does otherwise, an index greater than N-1 or less then -N causes an out-of-bounds error in lists and arrays.


Implicit indexing for nthnth 的な暗黙の要素指定)

暗黙の要素指定は、リストとアレイの要素や文字列中の文字を取り出す nth の代わりに使えます:
Implicit indexing can be used instead of nth to retrieve the elements of a list or array or the characters of a string:

(set 'lst '(a b c (d e) (f g)))

(lst 0)     a      ; same as (nth 0 lst)
(lst 3)     (d e)
(lst 3 1)   e      ; same as (nth '(3 1) lst)
(lst -1)    (f g)

(set 'myarray (array 3 2 (sequence 1 6)))

(myarray 1)      (3 4)
(myarray 1 0)    3
(myarray 0 -1)   2

("newLISP" 3)    "L"

; indexing strings in UTF8 enabled versions
 ("我能吞下玻璃而不伤身体。" 3)  "下"

インデックスにはリストも使えます。 その際の暗黙の要素指定は pushpop のようなインデックス・ベクターを引数とする関数で使い、また refref-all のようなインデックス・ベクターを生成する関数もあります。
Indices may also be supplied from a list. In this way, implicit indexing works together with functions that take or produce index vectors, such as push, pop, ref and ref-all.

(lst '(3 1))                 e
(set 'vec (ref 'e lst))      (3 1)
(lst vec)                    e

; an empty index vector yields the original list or array

(lst '())   (set 'lst '(a b c (d e) (f g)))

暗黙の要素指定は newLISP の構文ルールを壊しませんが、s式のファンクタ(関数オブジェクト)位置において、他のデータ型に対する既存のルールを拡張することに注目してください。 オリジナルの Lisp では s式リストの第一要素が関数となり、残りの要素を引数とします。 newLISP ではリストがs式のファンクタ(関数オブジェクト)位置に置かれると、リスト自身が自己インデックス関数のように機能し、それに続くインデックスを引数に使います。(訳注:オリジナルの Lisp では newLISP のように、s式リストの第一要素にリストを置くことができません。)
Note that implicit indexing is not breaking newLISP syntax rules but is merely an expansion of existing rules to other data types in the functor position of an s-expression. In original Lisp, the first element in an s-expression list is applied as a function to the rest elements as arguments. In newLISP, a list in the functor position of an s-expression assumes self-indexing functionality using the index arguments following it.

暗黙の要素指定は明示形式よりも速く動作し、明示形式は内容によっては可読性を良くします。
Implicit indexing is faster than the explicit forms, but the explicit forms may be more readable depending on context.

UTF-8 版 newLISP では、文字列への暗黙の要素指定や nth の使用は、1バイト境界ではなく、文字境界で作用します。
Note that in the UTF-8–enabled version of newLISP, implicit indexing of strings or using the nth function work on character rather than single-byte boundaries.


Implicit indexing and the default functor(暗黙の要素指定とデフォルト ファンクタ)

デフォルト・ファンクタ は、コンテキスト内でコンテキスト自身と同じ名前を持つファンクタ(関数オブジェクト)です。 コンテキスト・デフォルト・ファンクタ の章を見てください。 デフォルト・ファンクタは、リストを参照する機構として用意された暗黙の要素指定と一緒に使うことができます。
The default functor is a functor inside a context with the same name as the context itself. See The context default function chapter. A default functor can be used together with implicit indexing to serve as a mechanism for referencing lists:

(set 'MyList:MyList '(a b c d e f g))

(MyList 0)    a
(MyList 3)    d
(MyList -1)   g

(3 2 MyList)  (d e)
(-3 MyList)   (e f g)

(set 'aList MyList)

(aList 3)   d

この例で aListMyList:MyList をコピーすることなく、参照しています。 このコンテキストについての詳細情報はコンテキストを含む変数を見てください。
In this example, aList references MyList:MyList, not a copy of it. For more information about contexts, see Variables holding contexts.

インデックスされたデフォルト・ファンクタは、次の例で示すように setf と共に使うこともできます:
The indexed default functor can also be used with setf as shown in the following example:

(set 'MyList:MyList '(a b c d e f g))

(setf (MyList 3) 999)    999
(MyList 3)               999

MyList:MyList            (a b c 999 e f g)

Implicit indexing for rest and slicerestslice 的な暗黙の要素指定)

restslice 的な暗黙形式は、リストに先行する一つないし二つの数値で形成され、それぞれオフセットと長さを表します。 長さが負数の場合は、リストや文字列の終端から数えます(訳注:この場合、終端を 0 と数えるので、リストや文字列の終端まで切り出す時は負数の長さを指定できない):
Implicit forms of rest and slice can be created by prepending a list with one or two numbers for offset and length. If the length is negative it counts from the end of the list or string:

(set 'lst '(a b c d e f g))
; or as array
(set 'lst (array 7 '(a b c d e f g)))

(1 lst)       (b c d e f g)
(2 lst)       (c d e f g)
(2 3 lst)     (c d e)
(-3 2 lst)    (e f)
(2 -2 lst)    (c d e)

; resting and slicing is always on 8-bit char borders
; even on UTF8 enabled versions

(set 'str "abcdefg")

(1 str)       "bcdefg"
(2 str)       "cdefg"
(2 3 str)     "cde"
(-3 2 str)    "ef"
(2 -2 str)    "cde"

UTF-8 版 newLISP で、(訳注:文字列に使う)関数 restfirstlast はマルチバイト境界で作用します。 しかし、restslice 的な暗黙の要素指定形式は常に 1 バイト境界で作用するので、(訳注:UTF-8 版 newLISP でも)バイナリ・データに使えます。 正規表現関数 findregex からのオフセットと長さの結果も 1 バイト単位でカウントされるので、slice やその暗黙形式と一緒に使えます。
The functions rest, first and last work on multi-byte character boundaries in UTF-8 enabled versions of newLISP. But the implicit indexing forms for slicing and resting will always work on single-byte boundaries and can be used for binary content. Offset and length results from the regular expression functions find and regex are also in single-byte counts and can be further processed with slice or it's implicit form.


Modify references in lists, arrays and strings(文字列、リスト、アレイの参照変更)

インデックスで参照されるリスト、アレイ、文字列の部分は setf を使って変更可能です:
Parts in lists, arrays and strings referenced by indices can be modified using setf:

; lists

(set 'lst '(a b c d (e f g)))

(lst 1)  b

(setf (lst 1) 'z)  z

lst  (a z c d (e f g))

(setf (lst -1) '(E F G))  (E F G)

lst  (a z c d (E F G))

; arrays

(set 'myarray (array 2 3 (sequence 1 6)))  ((1 2 3) (4 5 6))

(setf (myarray 1 2) 66)  66

myarray  ((1 2 3) (4 5 66))

; strings

(set 's "NewLISP")

(setf (s 0) "n")  "n"

s  "newLISP"

全部が要素だけでも入れ子のリストでもアレイでも、この方法を使って変更できます。 暗黙の restslice を使って取り出す部分リストや部分アレイは、setf を使って直接置き換えることができません。要素毎に置き換えましょう。 文字列では、一度に置き換えられるのは一文字だけですが、複数文字からなる文字列に置き換えることは可能です。
Note that only full elements or nested lists or arrays can be changed this way. Slices or rest parts of lists or arrays as used in implicit resting or slicing cannot be substituted at once using setf, but would have to be substituted element by element. In strings only one character can be replaced at a time, but that character can be replaced by a multi-character string.


§ )

13. Destructive versus nondestructive functions(破壊的 対 非破壊的関数)

newLISP 組込の多くは非破壊的(副作用 無し)で、既存のオブジェクトに触らず残しますが、その代わりに新しいオブジェクトを作ります。 とは言え、数は少ないですが、変数・リスト・アレイ・文字列の内容を変更する 関数もあります:
Most of the primitives in newLISP are nondestructive (no side effects) and leave existing objects untouched, although they may create new ones. There are a few destructive functions, however, that do change the contents of a variable, list, array, or string:

functiondescription
++ 整数モードで数値を加算する
increments numbers in integer mode
-- 整数モードで数値を減算する
decrements numbers in integer mode
bind リストの連想変数を束縛する
binds variable associations in a list
constant 変数の内容を設定し、それをプロテクトする
sets the contents of a variable and protects it
extend リストか文字列を拡張する
extends a list or string
dec 変数、リスト、アレイで参照される数値を減算する
decrements a number referenced by a variable, list or array
define 変数の内容を設定する
sets the contents of a variable
define-macro 変数の内容を設定する
sets the contents of a variable
inc 変数、リスト、アレイで参照される数値を加算する
increments a number referenced by a variable, list or array
let ローカル変数を宣言し、初期化する
declares and initializes local variables
letn 入れ子の let のように、ローカル変数を初期化する
initializes local variables incrementally, like nested lets
letex 式中にローカル変数を展開し、その後評価する
expands local variables into an expression, then evaluates
net-receive バッファ変数を読み取る
reads into a buffer variable
pop リストや文字列から要素を取り出す
pops an element from a list or string
pop-assoc 連想リストから連想を取り去る
removes an association from an association list
push リストや文字列に新要素を挿入する
pushes a new element onto a list or string
read バッファ変数を読み取る
reads into a buffer variable
receive 親または子プロセスからメッセージを受け取る
receives a message from a parent or child process
replace リストや文字列内の要素を置換する
replaces elements in a list or string
reverse リストや文字列の並びを逆にする
reverses a list or string
rotate リストや文字列の文字の並びを回転する
rotates the elements of a list or characters of a string
set 変数の内容を設定する
sets the contents of a variable
setf setq シンボル、リスト、アレイ、文字列の内容を設定する
sets the contents of a variable, list, array or string
set-ref 入れ子リスト中の要素を検索し、置き換える
searches for an element in a nested list and replaces it
set-ref-all 入れ子リスト中の要素を検索し、全ての検出を置き換える
searches for an element in a nested list and replaces all instances
sort リストやアレイの要素を並べ替える
sorts the elements of a list or array
swap リストや文字列内の二つの要素を入れ替える
swaps two elements inside a list or string
write ファイルや文字列バッファに文字列を書き込む
write a string to a file or string buffer


Make a destructive function non-destructive(破壊的関数の非破壊的関数化)

破壊的関数の中には、目標オブジェクトを関数 copy で包み、非破壊的関数にできるものもあります。
Some destructive functions can be made non-destructive by wrapping the target object into the copy function.

(set 'aList '(a b c d e f))

(replace 'c (copy aList))  (a b d e f)

aList  (a b c d e f)

aList のリストは、変更されずに残っています。
The list in aList is left unchanged.


§ )

14. Early return from functions, loops, and blocks(関数、ループ、ブロックからの早期脱出)

以下の記述は、ループや begin 式内のフロー制御を中断する方法です。
What follows are methods of interrupting the control flow inside both loops and the begin expression.

ループ機能 dolistdotimes には、ループから早期に脱出する条件式をオプションで取ることができます。 catchthrow はループ本体から脱出する汎用形式であり、他の形式または制御ブロックに適用することもできます。
The looping functions dolist and dotimes can take optional conditional expressions to leave the loop early. catch and throw are a more general form to break out of a loop body and are also applicable to other forms or statement blocks.


Using catch and throwcatchthrow の使用)

newLISP は関数型言語なので、関数や繰り返しからの脱出に break 宣言文や return 宣言文を使いません。 代わりに、関数 catchthrow を使って、関数や繰り返しのいかなる場所からも脱出できます:
Because newLISP is a functional language, it uses no break or return statements to exit functions or iterations. Instead, a block or function can be exited at any point using the functions catch and throw:

(define (foo x)
    ...
    (if condition (throw 123))
    ...
    456
)
									 
;; if condition is true

(catch (foo p))   123
									 
;; if condition is not true
									 
(catch (foo p))   456

ループからの脱出も同じ方法で作動します:
Breaking out of loops works in a similar way:

(catch
    (dotimes (i N)
        (if (= (foo i) 100) (throw i))))

 value of i when foo(i) equals 100

この例は、繰り返しを N 回実行する前に脱出する方法を示しています。
The example shows how an iteration can be exited before executing N times.

throw を使えば、複数の場所からの戻りを記述できます:
Multiple points of return can be coded using throw:

(catch (begin
    (foo1)
    (foo2)
    (if condition-A (throw 'x))
    (foo3)
    (if condition-B (throw 'y))
    (foo4)
    (foo5)))

condition-A が真なら xcatch 式から戻り、condition-B が真なら戻り値は y になります。 それ以外では、foo5 の結果が戻り値として使われます。
If condition-A is true, x will be returned from the catch expression; if condition-B is true, the value returned is y. Otherwise, the result from foo5 will be used as the return value.

catch の代わりとして、 誤ったコードやユーザ定義例外によって起こるエラーを捕まえるために、関数error-event が使えます。
As an alternative to catch, the error-event function can be used to catch errors caused by faulty code or user-initiated exceptions.

関数 throw-errorは、ユーザ定義エラーを発生するために使います。
The throw-error function may be used to throw user-defined errors.


Using and and orandor の使用)

論理関数 andor を使って、宣言文ブロックに内包する関数の論理値結果次第で脱出するよう構成できます:
Using the logical functions and and or, blocks of statements can be built that are exited depending on the Boolean result of the enclosed functions:

(and
    (func-a)
    (func-b)
    (func-c)
    (func-d))

この and 式はブロック中の関数が nil() (empty list) を返すと、すぐに戻ります。 先行する関数群がどれもブロックからの脱出を起こさなければ、最後の関数の結果が返ります。
The and expression will return as soon as one of the block's functions returns nil or an () (empty list). If none of the preceding functions causes an exit from the block, the result of the last function is returned.

or も同じようにして使えます:
or can be used in a similar fashion:

(or
    (func-a)
    (func-b)
    (func-c)
    (func-d))

この or 式の結果を返すのは nil でもなく() でもない 値を返す最初の関数です。
The result of the or expression will be the first function that returns a value which is not nil or ().


§ )

15. Dynamic and lexical scoping(ダイナミック・スコープとレキシカル・スコープ)

(訳注:ダイナミック・スコープ(動的スコープ)とレキシカル・スコープ(構文スコープ)については、 以下が参考になります。  )

newLISP はコンテキスト内で ダイナミック・スコープを使っています。 コンテキストはレキシカルに閉じた名前空間です。 この方法により、newLISP のプログラム部品は レキシカル・スコープ の利点を取る別々の名前空間で活かされます。
newLISP uses dynamic scoping inside contexts. A context is a lexically closed namespace. In this way, parts of a newLISP program can live in different namespaces taking advantage of lexical scoping.

ラムダ式の変数シンボルが引数に束縛されると、古い束縛はスタックにプッシュされます。 ラムダ式から離れると、newLISP が自動的に元の変数束縛に復帰させます。
When the parameter symbols of a lambda expression are bound to its arguments, the old bindings are pushed onto a stack. newLISP automatically restores the original variable bindings when leaving the lambda function.

次の例はダイナミック・スコープ の動作を示しています。 ここでボールドのテキストは newLISP の出力です:
The following example illustrates the dynamic scoping mechanism. The text in bold is the output from newLISP:

> (set 'x 1)
1
> (define (f) x)
(lambda () x)
> (f)
1
> (define (g x) (f))
(lambda (x) (f))
> (g 0)
0
> (f)
1 
> _

変数 x は最初 1 に設定されています。 しかし、(g 0) が呼ばれて x0 に束縛されます。だから、(g 0) 実行中、(f) の出力する x0 になります。 (g 0) の実行後に (f) を呼び出すと、再び x1 として出力します。
The variable x is first set to 1. But when (g 0) is called, x is bound to 0 and x is reported by (f) as 0 during execution of (g 0). After execution of (g 0), the call to (f) will report x as 1 again.

これが、ローカル変数の束縛が関数内部でのみ起こる C や Java のような言語で見られる レキシカル・スコープ 動作との違いです。 C のようなレキシカル・スコープ言語では、(f) はシンボル x のグローバル束縛として、常に 1 を出力します。
This is different from the lexical scoping mechanisms found in languages like C or Java, where the binding of local parameters occurs inside the function only. In lexically scoped languages like C, (f) would always print the global bindings of the symbol x with 1.

次のユーザ定義関数において、関数の引数と同じ名前の変数名をクォート付きシンボルで渡すことが、名前の衝突を起こすことに着目してください:
Be aware that passing quoted symbols to a user-defined function causes a name clash if the same variable name is used as a function parameter:

(define (inc-symbol x y) (inc (eval x) y))
(set 'y 200)
(inc-symbol 'y 123)   246
y                     200  ; y is still 200

グローバル y は関数の第二引数と同じシンボル名なので、 inc-symbol は 246 (123 + 123) を返します。グローバル y を影響を受けずに残ります。 ダイナミック・スコープの変数補足 はユーザ定義関数に対してシンボル参照を渡す時、不利になります。 newLISP は変数補足を避けるいくつかの方法を提供しています。
Because the global y shares the same symbol as the function's second parameter, inc-symbol returns 246 (123 + 123), leaving the global y unaffected. Dynamic scoping's variable capture can be a disadvantage when passing symbol references to user-defined functions. newLISP offers several methods to avoid variable capture.

インターフェイスや関数ライブラリを作成する時は、コンテキストを使って関連する関数をグループ化すべきです。 これにより、レキシカルな〝壁〟で関数が囲われ、関数呼び出し時の変数名衝突が回避されます。
〝〟 Contexts should be used to group related functions when creating interfaces or function libraries. This surrounds the functions with a lexical "fence", thus avoiding variable name clashes with the calling functions.

newLISP はレキシカル・スコープの異なる形式でコンテキストを使います。 詳細な情報はコンテキストデフォルト・ファンクタの章を見てください。
newLISP uses contexts for different forms of lexical scoping. See the chapters Contexts and default functors for more information.


§ )

16. Contexts(コンテキスト)

newLISPでは、コンテキスト(contexts) と呼ばれる名前空間でシンボルを分離できます。 各コンテキストは、他の全てのコンテキストから隔離された個別のシンボル表を持っています。 一コンテキスト内のシンボルは他のコンテキストからは見えませんので、異なるコンテキストで同じ名前を使っても衝突しません。
In newLISP, symbols can be separated into namespaces called contexts. Each context has a private symbol table separate from all other contexts. Symbols known in one context are unknown in others, so the same name may be used in different contexts without conflict.

コンテキストは隔離された変数と関数の定義からなるモジュールの構築に使われます。 また、キー・値対の辞書を作るためにも使えます。 コンテキストはコピー可能で、動的に変数を割り当てられ、引数としても渡せます。 newLISP におけるコンテキストはレキシカルに分離された名前空間を持ちますので、レキシカル・スコープ によるプログラミングとプログラミングのソフトウェア・オブジェクト形式を可能にします。
Contexts are used to build modules of isolated variable and function definitions. They also can be used to build dictionaries fo key values pairs. Contexts can be copied and dynamically assigned to variables or passed as arguments by reference. Because contexts in newLISP have lexically separated namespaces, they allow programming with lexical scoping and software object styles of programming.

コンテキストはシンボルのルート部分に明示されているか、コンテキスト MAIN です。 この章では、コンテキスト・シンボルに大文字を使っていますが、小文字も使えます。
Contexts are identified by symbols that are part of the root or MAIN context. Although context symbols are uppercased in this chapter, lowercase symbols may also be used.

コンテキスト MAIN はコンテキスト名であると同時に、組込関数のシンボル及び truenil のような特殊シンボルを保持しています。 コンテキスト MAIN は newLISP を走らせる度に自動的に生成されます。 MAIN の全シンボルを見るには newLISP 開始後、次の式を入力してみてください:
In addition to context names, MAIN contains the symbols for built-in functions and special symbols such as true and nil. The MAIN context is created automatically each time newLISP is run. To see all the symbols in MAIN, enter the following expression after starting newLISP:

(symbols)

MAIN の全シンボルで使われているコンテキストを見るには:
To see all symbols in MAIN pointing to contexts:

(filter context? (map eval (symbols)))

現在のコンテキストが MAIN 以外にある時、MAIN にある全コンテキスト・シンボルを見るには:
To seel all context symbols in MAIN when MAIN is not the current context:

(filter context? (map eval (symbols MAIN)))

Symbol creation in contexts(コンテキストでのシンボル生成)

次の規則により、 作成したシンボルがどのコンテキストに割り当てられるかが明確になり、コンテキストへの理解が簡単になるでしょう。
The following rules should simplify the process of understanding contexts by identifying to which context the created symbols are being assigned.

  1. newLISP の各式の解析と翻訳は、トップ階層から始まります。 この解析中に全シンボルを生成します。 式は翻訳された後に、評価されます。
    newLISP first parses and translates each expression starting at the top level. All symbols are created during this phase. After the expression is translated, it gets evaluated.

  2. 関数 loadsymeval-string が呼ばれた時、newLISP はシンボルを最初に見つけた時、生成します。 newLISP はソースの読み込み時に、評価が起こる にシンボルを生成します。 関数 reader-event は、式を読み込み翻訳するがそれを評価する前に、その式を検査できます。 関数 read-expr は、newLISP のソースを評価することなく、読み込み翻訳するためだけに使えます。
    A symbol is created when newLISP first sees it, while calling the load, sym, or eval-string functions. When newLISP reads a source file, symbols are created before evaluation occurs. The reader-event function can be used to inspect the expression after reading and translating but before evaluation. The read-expr function can be used to read and translate newLISP source without evaluation.

  3. コード翻訳中に見知らぬシンボルに出会うと、その定義の検索を現在のコンテキスト内で始めます。 検索に失敗すると、MAIN 内で組込関数、コンテキスト、グローバル変数において検索を続けます。 定義が見つからなければ、そのシンボルが現在のコンテキスト内にローカルに生成されます。
    When an unknown symbol is encountered during code translation, a search for its definition begins inside the current context. Failing that, the search continues inside MAIN for a built-in function, context, or global symbol. If no definition is found, the symbol is created locally inside the current context.

  4. いったんシンボルが生成され、特定のコンテキストに割り当てられると、 そのシンボルは、関数 delete を使って削除されるまで、そのコンテキストに恒久的に従属します。
    Once a symbol is created and assigned to a specific context, it will belong to that context permanently or until it is deleted using the delete function.

  5. ユーザ定義関数の評価の際、そのシンボルを持っている名前空間にコンテキストが切り替わります。
    When a user-defined function is evaluated, the context is switched to the name-space which owns that symbol.

  6. コンテキスト切り替えは loadsymeval-string の間のシンボル生成にのみ、影響を及ぼします。 ロードされたファイルのトップ階層でコンテキスト切り替えが起こる時以外は、load はデフォルトで MAIN にロードします。 より良い使い方は、関数symeval-string を使う時に、コンテキストを常に指定することです。 コンテキスト切り替えは関数内部でなく、通常プログラムのトップ階層でのみ起こります。
    A context switch only influences symbol creation during load, sym, or eval-string. load by default loads into MAIN except when context switches occur on the top level of the file loaded. For better style, the context should always be specified when the functions sym and eval-string are used. A context switch should normally only be made on the top level of a program, never inside a function.


Creating contexts(コンテキスト生成)

コンテキストは関数 context の使用または暗黙の生成、いずれかで生成されます。 最初の方法は同じコンテキストに従属する多量のコードを書く時に使われます:
Contexts can be created either by using the context function or via implicit creation. The first method is used when writing larger portions of code belonging to the same context:

(context 'FOO)

(set 'var 123)

(define (func x y z)
    ... )

(context MAIN)

コンテキストがまだ存在していないなら、コンテキスト・シンボルはクォートされていなければなりません。 コンテキストは、それ自身に評価されるので、MAIN のように既に存在するコンテキストはクォートを必要としません。
If the context does not exist yet, the context symbol must be quoted. If the symbol is not quoted, newLISP assumes the symbol is a variable holding the symbol of the context to create. Because a context evaluates to itself, already existing contexts like MAIN do not require quoting.

上記 newLISP コードを読み込む時、最初の宣言文 (context 'FOO) が評価されます。 これが newLISP に FOO への名前空間切り替えを起こさせ、残りの式を読み込んで評価する際に、以下のシンボル varxyz 全てがコンテキスト FOO 内に生成されます。
When newLISP reads the above code, it will read, then evaluate the first statement: (context 'FOO). This causes newLISP to switch the namespace to FOO and the following symbols var, x, y and z will all be created in the FOO context when reading and evaluating the remaining expressions.

コンテキスト・シンボルは変更から保護されています。一回でもコンテキスト用に使われたシンボルは、delete を使わなければ、他の用途に使うことはできません。
A context symbol is protected against change. Once a symbol refers to a context, it cannot be used for any other purpose, except when using delete.

名前空間 FOO の外から varfunc を参照するには、コンテキスト名の先付けが必要です:
To refer to var or func from anywhere else outside the FOO namespace they need to be prefixed with the context name:

FOO:var  123

(FOO:func p q r)

注記、上記例で名前空間 FOO に属しているのは func だけです。 シンボル p q r は全て、FOO:func の呼び出しで作られますが、現在のコンテキストの一部です。
Note, that in the above example only func belongs to the FOO name space the symbols p q r all are part of the current context from which the FOO:func call is made.

コンテキストに所属する全てのシンボルを表示するために、関数 symbols が使えます:
The symbols function is used to show all symbols belonging to a context:

(symbols FOO)  (FOO:func FOO:var FOO:x FOO:y FOO:z)

; or from inside the context symbols are shown without context prefix
(context FOO)  (func x y z)
(sumbols)

Implicitly creating contexts(コンテキストの暗黙の生成)

まだ存在していないコンテキストが参照された時は、暗黙に生成されます。 関数 context とは違い、コンテキストが切り替わりません。 続く宣言文は、全て MAIN コンテキスト内で実行されます:
A context is implicitly created when referring to one that does not yet exist. Unlike the context function, the context is not switched. The following statements are all executed inside the MAIN context:

> (set 'ACTX:var "hello")
"hello"
> ACTX:var
"hello"
> _

コンテキスト名を先付けしたシンボルだけが、コンテキストのシンボルになることに気をつけてください:
Note that only the symbols prefixed with their context name will be part of the context:

(define (ACTX:foo x y) 
    (+ x y))

上記コードが MAIN にロードされると、foo のみが ACTX のシンボルです。 シンボル xy は、まだ MAIN のシンボルです。 ACTX:foo の構成要素を全て ACTX コンテキスト内に作るには、 ACTX を先付するか、 トップ階層でコンテキスト切り替えを実施してから、関数を定義する必要があります。
When above code is loaded in MAIN only foo will be part of ACTX. The symbols x and y will still be part of MAIN. To make all locals of ACTX:foo members of the ACTX context, they would either have to be prefixed with ACTX, or the whole funtion must be preceded by a context switch satement at the top level:

(context 'ACTX)
(define (foo x y)
    (+ x y)
(context MAIN

;; above same as

(define (ACTX:foo ACTX:x ACTX:y)
    (+ ACTX:x ACTX:y))

Loading module files(モジュール・ファイルのロード)

コマンドラインで load を使ってソース・ファイルをロードしている時や関数 eval-string または sym を実行している時は、関数 context が全てのシンボルと関数定義をどの名前空間に置くべきかを newLISP ソース・コード・リーダー に知らせます:
When loading source files on the command-line with load, or when executing the functions eval-string or sym, the context function tells the newLISP source code reader in which namespace to put all of the symbols and definitions:

;;; file MY_PROG.LSP
;;
;; everything from here on goes into GRAPH
(context 'GRAPH)
				 
(define (draw-triangle x y z)
    (…))

(define (draw-circle)
    (…))
									 
;; show the runtime context, which is GRAPH
(define (foo)
    (context))
									 
;; switch back to MAIN
(context 'MAIN)
				 
;; end of file					

関数 draw-triangledraw-circle—変数 xyz を伴う—はコンテキスト GRAPH の部品です。 これらのシンボルは GRAPH にとってのみ既知です。 これらの関数を他のコンテキストから呼び出すには GRAPH: を先付けします:
The draw-triangle and draw-circle functions — along with their x, y, and z parameters — are now part of the GRAPH context. These symbols are known only to GRAPH. To call these functions from another context, prefix them with GRAPH:

(GRAPH:draw-triangle 1 2 3)
(GRAPH:foo)   GRAPH										

最後の宣言文は、実行中のコンテキストを(function foo の context である)GRAPH に切り替える方法です。
The last statement shows how the runtime context has changed to GRAPH (function foo's context).

他のコンテキストからシンボル同士を比較する時は、シンボルの名前とコンテキストの両方を使います。 全修飾シンボルから名前部分を取り出すには関数 term を使います。
A symbol's name and context are used when comparing symbols from different contexts. The term function can be used to extract the term part from a fully qualified symbol.

;; same symbol name, but in different context
(= 'A:val 'B:val)                     nil
(= (term 'A:val) (term 'B:val))       true
(= (prefix 'A:val) (prefix 'B:val))   nil

注記:上記例のシンボルが ' (single quote) でクォートされているのは、シンボルのコンテキストではなく、シンボル自身を対象にしているからです。
Note: The symbols in above example are quoted with a ' (single quote) because we are interested in the symbol itself, not in the contents of the symbol.


Global scope(グローバル スコープ)

デフォルトでは組込関数と niltrue のような特殊シンボルのみが、MAIN 以外のコンテキスト内でも見ることができます。 どのコンテキストでもシンボルが見られるようにするには関数 global を使います:
By default, only built-in functions and symbols like nil and true are visible inside contexts other than MAIN. To make a symbol visible to every context, use the global function:

(set 'aVar 123)  123
(global 'aVar)   aVar

(context 'FOO)   FOO

aVar             123

global 宣言文を使わなければ、二番目の aVar123 の代わりに nil を返すでしょう。 FOO が前もって定義されたシンボル(この例では aVar)を持っているなら、代わりに—グローバルのシンボルではなく—その シンボル(訳注:FOO:aVar)の値が返ります。 コンテキスト MAIN 上でのみ、シンボルをグローバルにできることに注意してください(訳注:関数globalMAIN 上でしか使えないということ)。
Without the global statement, the second aVar would have returned nil instead of 123. If FOO had a previously defined symbol (aVar in this example) that symbol's value — and not the global's — would be returned instead. Note that only symbols from the MAIN context can be made global.

関数 global を使って、いったんコンテキストに対して透過にしてしまうと、(訳注:delete を使って削除しない限り)再びシンボルを隠すことはできません。
Once it is made visible to contexts through the global function, a symbol cannot be hidden from them again.


Symbol protection(シンボル保護)

関数 constant を使うことによって、 シンボルは設定され、同時に変更から保護されます:
By using the constant function, symbols can be both set and protected from change at the same time:

> (constant 'aVar 123)   123
> (set 'aVar 999)
ERR: symbol is protected in function set : aVar
>_

constant と global の両方が必要なシンボルを一遍に定義できます:
A symbol needing to be both a constant and a global can be defined simultaneously:

(constant (global 'aVar) 123)

現在のコンテキストで constant により保護されたシンボルを再び上書きできるのは、関数 constant の使用です。(訳注:現在のコンテキストのシンボルにしか constant を使えません)。 これにより、他のコンテキストにおけるコードによる上書きからシンボルが保護されます。
In the current context, symbols protected by constant can be overwritten by using the constant function again. This protects the symbols from being overwritten by code in other contexts.


Overwriting global symbols and built-ins(グローバル・シンボルと組込の上書き)

コンテキスト内でコンテキスト自身 のシンボルを先付けすることにより、グローバルにされたシンボルや組込関数のシンボルを上書きできます:
Global and built-in function symbols can be overwritten inside a context by prefixing them with their own context symbol:

(context 'Account)

(define (Account:new …)
    (…))

(context 'MAIN)

この例では、組込関数 new が異なる関数として、コンテキスト Account専用の Account:new に上書きされます。
In this example, the built-in function new is overwritten by Account:new, a different function that is private to the Account context.


Variables containing contexts(コンテキストを含む変数)

コンテキストの参照に変数が使えます:
Variables can be used to refer to contexts:

(set 'FOO:x 123)

(set 'ctx FOO)     FOO

ctx:x              123

(set 'ctx:x 999)   999

FOO:x              999

関数を書く時、実行中に異なるコンテキストを参照する必要がある場合や、定義中に存在しないコンテキストを使う必要がある場合には、コンテキスト変数が使えます:
Context variables are useful when writing functions, which need to refer to different contexts during runtime or use contexts which do not exist during definition:

(define (update ctx val)
    (set 'ctx:sum val)
    (ctx:func 999)
)

(context 'FOO)
(define (func x)
    (println "=>" x))
(context MAIN)

続いては、上記定義を使ったターミナル・セッションを示します。 プログラムの出力はボールドで示しています:
The following shows a terminal session using above definitions. The program output is shown in bold-face:

> (update FOO 123)
=> 999

> FOO:sum
123
>

関数 update は第一変数として渡されるコンテキスト次第で、同じ関数でも異なる動作を表示します。
The same one function update can display different behavior depending on the context passed as first parameter.


Sequence of creating or loading contexts(コンテキストの生成手順)

コンテキストを生成する時あるいはロードする時の一連の手続き(訳注:コンテキストでのシンボル生成を参照)が予期しない結果をもたらすことがあります。 demo と呼ばれるファイルに次のコードを入力してみてください:
The sequence in which contexts are created or loaded can lead to unexpected results. Enter the following code into a file called demo:

;; demo - file for loading contexts
(context 'FOO)
(set 'ABC 123)
(context MAIN)

(context 'ABC)
(set 'FOO 456)
(context 'MAIN)

次に newLISP シェルでこのファイルをロードします:
Now load the file into the newlisp shell:

> (load "demo")
ERR: symbol is protected in function set : FOO
> _

ファイルのロードが FOO についてのエラー・メッセージを出しますが、ABC に対しては出しません。 最初のコンテキスト FOO がロードされた時、コンテキスト ABC はまだ存在しないのでローカル変数 FOO:ABC が生成されます。 ABC のロード時には、すでに FOO がグローバル・プロテクト・シンボルとして存在し、正常にプロテクトのフラグがセットされています。(訳注:だから FOO のエラーになったのです。)
Loading the file causes an error message for FOO, but not for ABC. When the first context FOO is loaded, the context ABC does not exist yet, so a local variable FOO:ABC gets created. When ABC loads, FOO already exists as a global protected symbol and will be correctly flagged as protected.

この場合でも、コンテキスト ABCFOO をローカル変数として使うことは可能で、ABC:FOO という風に明示的にコンテキストを先付けします。
FOO could still be used as a local variable in the ABC context by explicitly prefixing it, as in ABC:FOO.


Contexts as programming modules(プログラミング・モジュールとしてのコンテキスト)

newLISP ではソースをモジュールに区分けするために、主にコンテキストを使います。 こうすることで各モジュールが異なる名前空間で動作するので、モジュールはレキシカルに分離され、他のモジュールに同一のシンボル名があっても衝突しません。
Contexts in newLISP are mainly used for partitioning source into modules. Because each module lives in a different namespace, modules are lexically separated and the names of symbols cannot clash with identical names in other modules.

newLISP 配布の一部である modules には、モジュール・ファイルに関連する関数を置く方法や newLISPdoc ユーティリティを使ってモジュールを文書化する方法などの例があります。
The modules, which are part of the newLISP distribution, are a good example of how to put related functions into a module file, and how to document modules using the newLISPdoc utility.

最良のプログラミング習慣は、一ファイルが一モジュールを含み、ファイル名は使っているコンテキスト名と同じでなくとも、似ていることです:
For best programming practice, a file should only contain one module and the filename should be similar if not identical to the context name used:

;; file db.lsp, commonly used database functions

(context 'db)

;; Variables used throughout this namespace

(define db:handle)
(define db:host "http://localhost")

;; Constants

(constant 'Max_N 1000000)
(constant 'Path "/usr/data/")

;; Functions

(define (db:open ... )
    ... )

(define (db:close ... )
    ... )

(define (db:update ... )
    ... )

この例では、予め変数を定義しておく良い習慣を示しています。名前空間内のグローバル変数を定義したり、変化しない変数を constant として定義したりしておくことです。
The example shows a good practice of predefining variables, which are global inside the namespace, and defining as constants the variables that will not change.

ファイルが一個以上のコンテキストから構成されるなら、コンテキストの終りに MAIN への切り替えを明示しておくべきです:
If a file contains more than one context, then the end of the context should be marked with a switch back to MAIN:

;; Multi context file multi.lsp

(context 'A-ctx)
...
(context MAIN)

(context 'B-ctx)
...
(context MAIN)

(context 'C-ctx)
...
(context MAIN)

Contexts as data containers(データ・コンテナとしてのコンテキスト)

コンテキストはデータ・コンテナとしてよく使われます。例えばハッシュ似の辞書や設定データのようなものです:
Contexts are frequently uses as data containers, e.g. for hash-like dictionaries and configuration data:

;; Config.lsp - configuration setup

(context 'Config)

(set 'user-name "admin")
(set 'password "secret")
(set 'db-name "/usr/data/db.lsp")
...

;; eof

名前空間 Config をロードすると、全ての変数をメモリに一度で設定できます:
Loading the Config namespace will now load a whole variable set into memory at once:

(load "Config.lsp")

(set 'file (open Config:db-name "read"))
...
...

同様の状況を一つの全データ・セットとしてセーブすることもできます:
In a similar fashion a whole data set can be saved:

(save "Config.lsp" 'Config)

これに関する詳細は コンテキスト・オブジェクトの直列化シリアライズ の章で読んでください。
Read more about this in the section Serializing contexts.


Loading and declaring contexts(コンテキストのロードと宣言)

モジュール・ファイルは、関数 load を使ってロードされます。 プログラミング・プロジェクトが互いに参照する多数のモジュールからなる時、コンテキストをロードする前に起こり得るコンテキストの前方参照による問題を避けるために、コンテキストを予約宣言できます。
Module files are loaded using the load function. If a programming project contains numerous modules that refer to each other, they can be pre-declared to avoid problems due to context forward references that can occur before the loading of that context.

;; pre-declaring contexts, finish with Main to return
(map context '(Utilities Config Acquisition Analysis SysLog Main))

;; loading context module files
(load "Utilities.lsp" "Acquisition.lsp")
(load "http://192.168.1.34/Config.lsp") ; load module from remote location
(load "Analysis.lsp" "SysLog.lsp")

(define (run)
    ... )

(run)

;; end of file 

この例が示すように予約宣言してからロードすれば、宣言やロードの一連の手続き(訳注:コンテキストでのシンボル生成を参照)を気にする必要がありません。 まだロードされていないモジュールの変数や定義への前方参照が、全ての正しく翻訳されるからです。 コンテキスト・シンボルの誤用は、コンテキストがロードされる前に、エラー・メッセージが出ます。
When pre-declaring and loading modules as shown in the example, the sequence of declaration or loading can be neglected. All forward references to variables and definitions in modules not loaded yet will be translated correctly. Wrong usage of a context symbol will result in an error message before that context is loaded.

コンテキスト切り替えで始まっていないモジュールは、常に MAIN にロードされます。ただし、load 宣言文の最後のオプションで目標コンテキストを指定している時は別です。 リモート位置から HTTP 経由でモジュールをロードする際は、関数 load の引数に URL を取れます。
Modules not starting with a context switch are always loaded into MAIN except when the load statement specifies a target context as the last parameter. The load function can take URLs to load modules from remote locations, via HTTP.

load 宣言文終了後の現在のコンテキストは、常に load の前と同じです。
The current context after the load statement will always be the same as before the load.


Serializing contexts(コンテキスト・オブジェクトの直列化シリアライズ

直列化シリアライズすることは、ソフトウェア・オブジェクトをファイルやメモリ内の文字列に保存される文字ストリームに置き換えることで 持続性 をもたらします。 newLISP では、シンボルで参照されるもの全てが関数 save を使って、ファイルに直列化シリアライズ可能です。 シンボルと同様、コンテキストもコンテキスト名を使って保存されます:
Serialization makes a software object persistent by converting it into a character stream, which is then saved to a file or string in memory. In newLISP, anything referenced by a symbol can be serialized to a file by using the save function. Like other symbols, contexts are saved just by using their names:

(save "mycontext.lsp" 'MyCtx)              ; save MyCtx to mycontext.lsp

(load "mycontext.lsp")                     ; loads MyCtx into memory

(save "mycontexts.lsp" 'Ctx1 'Ctx2 'Ctx3)  ; save multiple contexts at once

詳細については、関数 save (上記内容) と source (newLISP 文字列への直列化シリアライズ) を見てください。
For details, see the functions save (mentioned above) and source (for serializing to a newLISP string).


§ )

17. The context default functor(コンテキスト・デフォルト・ファンクタ)

デフォルト・ファンクタ またはデフォルト・ファンクション は、その名前空間と同じ名前を持つシンボルかユーザ定義関数かマクロです。 コンテキストを関数の名前として使う時、またはs式の関数位置で使う時、 newLISP はデフォルト・ファンクションを実行します。
A default functor or default function is a symbol or user-defined function or macro with the same name as its namespace. When the context is used as the name of a function or in the functor position of an s-expression, newLISP executes the default function.

;; the default function

(define (Foo:Foo a b c) (+ a b c))

(Foo 1 2 3)   6

デフォルト・ファンクションが MAIN と違うコンテキストから呼ばれる時には、コンテキストがすでに存在しているか、コンテキストと関数シンボルを生成する前方宣言 が宣言されている必要があります:
If a default function is called from a context other than MAIN, the context must already exist or be declared with a forward declaration, which creates the context and the function symbol:

;; forward declaration of a default function
(define Fubar:Fubar)    

(context 'Foo)
(define (Foo:Foo a b c)
    …
    (Fubar a b)         ; forward reference
    (…))         ; to default function

(context MAIN)

;; definition of previously declared default function

(context 'Fubar)
(define (Fubar:Fubar x y)
    (…))

(context MAIN)

デフォルト・ファンクションはグローバル関数のように動作しますが、 それが呼ばれているコンテキストからはレキシカルに分離しています。
Default functions work like global functions, but they are lexically separate from the context in which they are called.

ラムダ関数やラムダ・マクロのように、デフォルト・ファンクションを mapapply で使うことができます。
Like a lambda or lambda-macro function, default functions can be used with map or apply.


Functions with memory(メモリとしての関数)

デフォルト・ファンクションはその名前空間内にあるレキシカルに隔離された静的変数を更新できます:
A default function can update the lexically isolated static variables contained inside its namespace:

;; a function with memory

(define (Gen:Gen x)
    (if Gen:acc
        (inc Gen:acc x)
        (setq Gen:acc x)))

(Gen 1)   1
(Gen 1)   2
(Gen 2)   4
(Gen 3)   7

gen:acc   7

関数 Gen が初めて呼ばれると、加算器に引数の値が設定されます。 関数が続けて呼ばれる度に Gen の加算器に引数の値が加算されていきます。
The first time the Gen function is called, its accumulator is set to the value of the argument. Each successive call increments Gen's accumulator by the argument's value.

この Gen:Gen の定義は、(context 'Gen)(context MAIN) 宣言文で囲むこと無しに、関数を関数名と同じ名前空間に置く方法を示しています。 この場合、明示的に名前空間を先付けしたシンボルだけが、コンテキスト Gen の中に置かれます。 上記例では、変数 xMAIN の部品のままです。
The definition of Gen:Gen shows, how a function is put in its own namespace without using the surrounding (context 'Gen) and (context MAIN) statements. In that case only symbols qualified by the namespace prefix will end up in the Gen context. In the above example the variable x is still part of MAIN.


Hash functions and dictionaries(ハッシュ機能と辞書)

名前空間 context にシンボルを置くことで使えるようになる機能がいくつかあります。 単純なハッシュ似の変数→値対の集合体として辞書のように使う時は、デフォルト・ファンクタ に初期値を与えずに使います:
There are several functions that can be used to place symbols into namespace contexts. When using dictionaries as simple hash-like collections of variable → value pairs, use the uninitialized default functor:

(define Myhash:Myhash) ; create namespace and default functor

; or as a safer alternative

(new Tree 'MyHash) ; create from built-in template

どちらの方法も MyHash の辞書空間とデフォルト・ファンクタを作ることができます。 二番目の手段の方が安全で、デフォルト・ファンクタ MyHash:MyHash を変更から守ることができます。 辞書として使う時は、名前空間のデフォルト・ファンクタnil を入れておく必要があります。 シンボル名に使える文字列は1022文字に制限され、コンテキストで使われるシンボル名にはアンダースコアが内部処理で先付けされます。 キー・値対の生成と(訳注:キーによる)値の呼び出しが簡単になります:
Either method can be used to make the MyHash dictionary space and default functor. The second method is safer, as it will protect the default functor MyHash:MyHash from change. The default functor in a namespace must contain nil to be used as a dictionary. The string used for the symbol name is limited to 1022 characters and internally an underscore is prepended to the symbol name used in the context. Creating key-value pairs and retrieving a value is easy:

(Myhash "var" 123) ; create and set variable/value pair

(Myhash "var")   123 ; retrieve value

; keys can be integers and will be converted to strings internally

(Myhash 456 "hello")

(Myhash 456)     "hello"

; internally an underscore is prepended to the symbol name

(symbols Myhash)   (Myhash:Myhash Myhash:_456 Myhash:_var)

この方法で作られるシンボル変数は、スペースや通常 newLISP のシンボル名としては許されない文字を含むこともできます:
Symbol variables created this way can contain spaces or other characters normally not allowed in newLISP symbol names:

(define Foo:Foo)
; or to protect the default functor from change
; (new Tree 'Foo)

(Foo "John Doe" 123)          123
(Foo "#1234" "hello world")   "hello world"
(Foo "var" '(a b c d))        (a b c d)

(Foo "John Doe")   123
(Foo "#1234")      "hello world"
(Foo "var")      (a b c d)

存在しないエントリは nil を返します:
An entry which doesn't exist will return nil:

(Foo "bar")     nil

エントリに nil を設定することは、そのエントリを名前空間から実際に削除します。
Setting an entry to nil will effectively delete it from the namespace.

名前空間の内容から連想リストが生成できます:
An association list can be generated from the contents of the namespace:

(Foo)  (("#1234" "hello world") ("John Doe" 123) ("var" (a b c d)))

このリストはソートされたキー‐>値ペアで、繰り返し操作にも使えます:
The list can also be used to iterate through the sorted key -> value pairs:

(dolist (item (Foo)) (println (item 0) " -> " (item 1)))

#1234 -> hello world
John Doe -> 123
var -> (a b c d)

辞書へのエントリはリストからも可能です:
Entries in the dictionary can also be created from a list:

(Foo '(("#1234" "hello world") ("John Doe" 123) ("var" (a b c d)))  Foo

多くの組込関数と同じように、ハッシュ式はその内容を直接変更可能な参照として返します:
Like many built-in functions hash expressions return a reference to their content which can be modified directly:

(pop (Foo "var"))  a

(Foo "var")  (b c d)

(push 'z (Foo "var"))  (z b c d)

(Foo "var")  (z b c d)

ハッシュ値に新しい値をセットする時、古い値をアナフォリック・システム変数 $it で参照することができます:
When setting hash values the anaphoric system variable $it can be used to refer to the old value when setting the new:

(Foo "bar" "hello world")

(Foo "bar" (upper-case $it))

(Foo "bar")  "HELLO WORLD"

ハッシュ値はsetf を使っても変更可能です:
Hash values also can be modified using setf:

(Foo "bar" 123)         123

(setf (Foo "bar") 456)  456

(Foo "bar")             456

ただし、ハッシュ関数の第二変数に値を与えたほうが短く書け、かつ高速です。
But supplying the value as a second parameter to the hash functions is shorter to write and faster.

辞書は簡単にファイルに保存でき、後で再ロードできます:
Dictionaries can easily be saved to a file and reloaded later:

; save dictionary
(save "Foo.lsp" 'Foo)

; load dictionary
(load "Foo.lsp")

内部的には、キー文字列がハッシュ内容のシンボルとして生成され、保存されています。 全てのキー文字列にはアンダースコア文字 _ が先付けされます。 このことにより、ディスクや HTTP 上からハッシュ名前空間をロードする際に必要となる setsym などのシンボルやデフォルト・シンボルへの上書きが予防されます。 次の違いに注意してください:
Internally the key strings are created and stored as symbols in the hash context. All key strings are prepended with an _ underscore character. This protects against overwriting the default symbol and symbols like set and sym, which are needed when loading a hash namespace from disk or over HTTP. Note the following difference:

(Foo)  (("#1234" "hello world") ("John Doe" 123) ("var" (a b c d)))

(symbols Foo)  (Foo:Foo Foo:_#1234 Foo:_John Doe Foo:_var)

一行目では、先付けにアンダースコア文字の無い文字列でハッシュ・シンボルが現れます。 二行目は、アンダースコア文字の先付けされた内部形式シンボルが現れます。
In the first line hash symbols are shown as strings without the preceding underscore characters. The second line shows the internal form of the symbols with prepended underscore characters.

名前空間 に関する詳細な手引きは Contexts の章を見てください。
For a more detailed introduction to namespaces, see the chapter on Contexts.


Passing data by reference(参照によるデータの受け渡し)

デフォルト・ファンクタ はデータ保持にも使えます。 このデータがリストか文字列なら、コンテキスト名をデータへの参照として使えます:
A default functor can also be used to hold data. If this data contains a list or string, the context name can be used as a reference to the data:

;; the default functor for holding data

(define Mylist:Mylist '(a b c d e f g))

(Mylist 3)  d 

(setf (Mylist 3) 'D)  D

Mylist:Mylist  (a b c D e f g)

;; access list or string data from a default functor

(first Mylist)  a

(reverse Mylist)  (g f e D c b a)

(set 'Str:Str "acdefghijklmnop") 

(upper-case Str)  "ACDEFGHIJKLMNOP"

多くの場合、newLISP は変数を値のコピー で渡します。 大規模リストや長大な文字列をユーザ定義関数やマクロに渡す際、これが潜在的な問題を引き起こします。 デフォルト・ファンクタを使った名前空間に入れられた文字列やリストは、自動的に参照で渡されます:
Most of the time, newLISP passes parameters by value copy. This poses a potential problem when passing large lists or strings to user-defined functions or macros. Strings and lists, which are packed in a namespace using default functors, are passed automatically by reference:

;; use a default functor to hold a list

(set 'Mydb:Mydb (sequence 1 100000))

(define (change-db obj idx value)
    (setf (obj idx) value))

; pass by context reference
(change-db Mydb 1234 "abcdefg")

(Mydb 1234)   "abcdefg"

リストか文字列の—他のデータ型でない—どちらかで呼び出される組込関数は引数として、参照で渡されるデータを受け取ることができます。 ユーザ定義関数なら、通常の変数を受け取るか、リストか文字列のデフォルト・ファンクタへの参照を渡すコンテキスト名を受け取ることができます。
Any argument of a built-in function calling for either a list or a string — but no other data type — can receive data passed by reference. Any user-defined function can take either normal variables, or can take a context name for passing a reference to the default functor containing a list or string.

覚えておいて欲しいのは、100 要素より少ないリストや 50000 文字より少ない文字列では、参照と値渡しの速度差は無視してよいほどだということです。 しかし、それ以上に大きなオブジェクトでは、参照と値渡しの速度とメモリ消費量の違いは検討に値します。
Note that on lists with less than about 100 elements or strings of less than about 50000 characters, the speed difference between reference and value passing is negligible. But on bigger data objects, differences in both speed and memory usage between reference and value passing can be significant.

組込関数とユーザ定義関数は引数として両者の型に対応しますが、コンテキスト名が渡される時、データは参照で渡されます。
Built-in and user-defined functions are suitable for both types of arguments, but when passing context names, data will be passed by reference.

参照によるデータ渡しにクォート付きシンボルを使うこともできますが、この方法には問題があります:
Quoted symbols can also be used to pass data by reference, but this method has disadvantages:

(define (change-list aList) (push 999 (eval aList)))

(set 'data '(1 2 3 4 5))

; note the quote ' in front of data
(change-list 'data)   (999 1 2 3 4 5)

data    (999 1 2 3 4 5)

この方法は理解し易く、簡単に使えますが、関数の変数名と同じシンボルが渡されると潜在的な変数捕捉 問題を引き起こします:
Although this method is simple to understand and use, it poses the potential problem of variable capture when passing the same symbol as used as a function parameter:

;; pass data by symbol reference

> (set 'aList '(a b c d))
(a b c d)
> (change-list 'aList)

ERR: list or string expected : (eval aList)
called from user defined function change-list
> 

この章の始めで、デフォルト・ファンクタを使う名前空間にデータをまとめる方法を紹介しました(訳注:ハッシュ機能と辞書のこと)。 データの保持に使えるコンテキストのシンボルは、デフォルト・ファンクタだけではありません。 欠点は、呼び出す関数で使われるシンボルがわかっている必要があることです:
At the beginning of the chapter it was shown how to package data in a name-space using a default functor. Not only the default functor but any symbol in context can be used to hold data. The disadvantage is that the calling function must have knowledge about the symbol being used:

;; pass data by context reference

(set 'Mydb:data (sequence 1 100000))

(define (change-db obj idx value)
    (setf (obj:data idx) value))

(change-db Mydb 1234 "abcdefg")

(nth 1234 Mydb:data)    "abcdefg"
; or
(Mydb:data 1234)    "abcdefg"

関数は変数 obj に名前空間を受け取りますが、アクセスするリストが名前空間(コンテキスト)のシンボル data にあることを知っていなければなりません。
The function receives the namespace in the variable obj, but it must have the knowledge that the list to access is contained in the data symbol of that namespace (context).


§ )

18. Functional object-oriented programming(関数的オブジェクト指向プログラミング)

関数的オブジェクト指向プログラミング (FOOP) は、次の五つの原理に基づいています:
Functional-object oriented programming (FOOP) is based on the following five principles:

以下の節は、 neglook.comMichael Michaels の企画による FOOP についての 短い入門書です。
The following paragraphs are a short introduction to FOOP as designed by Michael Michaels from neglook.com.


FOOP classes and constructors(FOOP クラスとコンストラクタ)

クラスの属性とメソッドは、オブジェクト・クラスの名前空間に保存されます。 オブジェクトの実体データは、この名前空間/コンテキストに保存されません。 クラス名前空間でのデータ変数は、オブジェクト特有の情報を含まない完全体として、オブジェクトのクラスのみを記述します。 new で新しいオブジェクト・クラスを生成する時、特定のオブジェクト・コンストラクタのテンプレートとして、包括的な FOOP オブジェクト・コンストラクタを使えます:
Class attributes and methods are stored in the namespace of the object class. No object instance data is stored in this namespace/context. Data variables in the class namespace only describe the class of objects as a whole but don't contain any object specific information. A generic FOOP object constructor can be used as a template for specific object constructors when creating new object classes with new:

; built-in generic FOOP object constructor
(define (Class:Class) 
    (cons (context) (args)))

; create some new classes

(new Class 'Rectangle)    Rectangle
(new Class 'Circle)       Circle

; create some objects using the default constructor

(set 'rect (Rectangle 10 20))    (Rectangle 10 20)
(set 'circ (Circle 10 10 20))    (Circle 10 10 20)

; create a list of objects
; building the list using the list function instead of assigning
; a quoted list ensures that the object constructors are executed

(set 'shapes (list (Circle 5 8 12) (Rectangle 4 8) (Circle 7 7 15)))
 ((Circle 5 8 12) (Rectangle 4 8) (Circle 7 7 15))

包括的な FOOP コンストラクタはあらかじめ定義されていて、直ちに (new Class ...) 宣言文から FOOP コードを始めることができます。
The generic FOOP constructor is already pre-defined, and FOOP code can start with (new Class ...) statements right away.

スタイルの問題として、新しいクラスは MAIN コンテキストでのみ生成すべきです。 違う名前空間に新しいクラスを生成すると、新しいクラス名に MAIN を先付しなくてはならず、宣言文をトップ・レベル上に置く必要があります:
As a matter of style, new classes should only be created in the MAIN context. If creating a new class while in a different namespace, the new class name must be prefixed with MAIN and the statement should be on the top-level:

(context 'Geometry)

(new Class 'MAIN:Rectangle)
(new Class 'MAIN:Circle)

...

new を使って名前空間クラスを生成することは、newLISP のコンテキストにクラス名を予約し、前方参照を容易にします。 同時に新しいクラスにとっては、新しいオブジェクトをインスタンス化するための簡易コンストラクタが定義されます。 慣習として、名前が名前空間であることを知らしめるために、クラス名を大文字で始めることを推奨します。
Creating the namespace classes using new reserves the class name as a context in newLISP and facilitates forward references. At the same time, a simple constructor is defined for the new class for instantiating new objects. As a convention, it is recommended to start class names in upper-case to signal that the name stands for a namespace.

new によるクラス生成の際に生成される簡易コンストラクタを上書きする方が便利な場合もあります。
In some cases, it may be useful to overwrite the simple constructor, that was created during class creation, with new:

; overwrite simple constructor 
(define (Circle:Circle x y radius)
    (list Circle x y radius))

コンストラクタはデフォルト(訳注:引数の初期値)も指定可能です:
A constructor can also specify defaults:

; constructor with defaults
(define (Circle:Circle (x 10) (y 10) (radius 3))
    (list Circle x y radius))

(Circle)  (Circle 10 10 3)

多くの場合、new を使った時に生成されるコンストラクタで十分であり、その上書きは必要ありません。
In many cases the constructor as created when using new is sufficient and overwriting it is not necessary.


Objects and associations(オブジェクト)

FOOP はオブジェクトをリストで表現します。 リストの第一要素はオブジェクトの種類やクラスを示し、残りの要素はデータになります。 次の宣言文は、前もって定義されたコンストラクタを使って、二つのオブジェクト を定義しています:
FOOP represents objects as lists. The first element of the list indicates the object's kind or class, while the remaining elements contain the data. The following statements define two objects using any of the constructors defined previously:

(set 'myrect (Rectangle 5 5 10 20))  (Rectangle 5 5 10 20)
(set 'mycircle (Circle 1 2 10))  (Circle 1 2 10)

生成されたオブジェクトは、それを生成するのに必要な関数と同一です (FOOP 故に) 。 同様な方法で入れ子のオブジェクトを生成可能です:
An object created is identical to the function necessary to create it (hence FOOP). Nested objects can be created in a similar manner:

; create classes
(new Class 'Person)
(new Class 'Address)
(new Class 'City)
(new Class 'Street)

; create an object containing other objects
(set 'JohnDoe (Person (Address (City "Boston") (Street 123 "Main Street"))))
 (Person (Address (City "Boston") (Street 123 "Main Street")))

FOOP のオブジェクトは関数に似ているばかりでなく、連想にも似ています。 名前でオブジェクトをアクセスするために関数 assoc を使うことができます:
Objects in FOOP not only resemble functions they also resemble associations. The assoc function can be used to access object data by name:

(assoc Address JohnDoe)  (Address (City "Boston") (Street 123 "Main Street"))

(assoc (list Address Street) JohnDoe)  (Street 123 "Main Street")

同様に assoc と一緒に setf を使って、オブジェクト・データを変更できます:
In a similar manner setf together with assoc can be used to modify object data:

(setf (assoc (list Address Street) JohnDoe) '(Street 456 "Main Street"))
 (Street 456 "Main Street")

このように、ストリート番号が 123 から 456 に変わります。
The street number has been changed from 123 to 456.

assoc 宣言文の AddressStreet にクォートを付ける必要がないことに注意してください。 データを割り付けるための set 宣言文:(set 'JohnDoe (Person ...)) でも同様です。 どちらの場合も、シンボルやシンボルのリストではなく、 それ自身に評価されるコンテキストと FOOP オブジェクトを扱っています。 クォート付きでも違いは起きません。
Note that in none of the assoc statements Address and Street need to carry quotes. The same is true in the set statement: (set 'JohnDoe (Person ...)) for the data part assigned. In both cases we do not deal with symbols or lists of symbols but rather with contexts and FOOP objects which evaluate to themselves. Quoting would not make a difference.


The colon : operator and polymorphism(コロン : 演算子と多態性)

newLISP でコロン文字 : は、主にコンテキスト・シンボルとシンボルの接続に使われ、シンボルを特定します。 二つ目の使い方としてのコロン関数は FOOP において、関数の用途を多態的に解決するために使われます。
In newLISP, the colon character : is primarily used to connect the context symbol with the symbol it is qualifying. Secondly, the colon function is used in FOOP to resolve a function's application polymorphously.

次のコードで定義されている二つの関数は area と呼ばれ、それぞれ異なる名前空間/クラスに属しています。 両関数は個別の異なるモジュールで定義されていますが、この場合、同じファイル上で定義されていて、context 宣言文で囲まれていません。 rectangle:areacircle:area というように、異なる名前空間に属しているだけです。 ローカル・パラメータ pcdxdy は、全て MAIN の部品ですが、気にする必要はありません。
The following code defines two functions called area, each belonging to a different namespace / class. Both functions could have been defined in different modules for better separation, but in this case they are defined in the same file and without bracketing context statements. Here, only the symbols rectangle:area and circle:area belong to different namespaces. The local parameters p, c, dx, and dy are all part of MAIN, but this is of no concern.

;; class methods for rectangles

(define (Rectangle:area)
    (mul (self 3) (self 4)))

(define (Rectangle:move dx dy)
    (inc (self 1) dx) 
    (inc (self 2) dy))

;; class methods for circles

(define (Circle:area)
    (mul (pow (self 3) 2) (acos 0) 2))

(define (Circle:move dx dy)
    (inc (self 1) dx) 
    (inc (self 2) dy))

areamove シンボルに : (colon) を先付することで、各オブジェクトのクラス関数を呼び出せます。 コロンとそれに続くシンボル間にスペースはいらず、newLISP が別々のエントリとして解析します。 コロンが変数を処理する関数として動作します:
By prefixing the area or move symbol with the : (colon), we can call these functions for each class of object. Although there is no space between the colon and the symbol following it, newLISP parses them as distinct entities. The colon works as a function that processes parameters:

(:area myrect)  200 ; same as (: area myrect)
(:area mycircle)  314.1592654 ; same as (: area mycircle)

;; map class methods uses curry to enclose the colon operator and class function

(map (curry :area) (list myrect mycircle))  (200 314.1592654)

(map (curry :area) '((Rectangle 5 5 10 20) (Circle 1 2 10)))  (200 314.1592654) 


;; objects are mutable (since v10.1.8)

(:move myrect 2 3)
(:move mycircle 4 5) 

myrect     (Rectangle 7 8 10 20)
mycircle   (Circle 5 7 10)

この例では、シンボル(rectangle:areacircle:area)が正しく特定され、コロンに続くシンボルとコンテキスト名(オブジェクト・リストの第一要素)に基づくオブジェクト・データに適用されています。
In this example, the correct qualified symbol (rectangle:area or circle:area) is constructed and applied to the object data based on the symbol following the colon and the context name (the first element of the object list).

呼び出し側は呼び出された目標オブジェクトを特定しますが、 メソッド定義には変数としてオブジェクトが含まれていないことに注意してください。 FOOP オブジェクトを変更する関数を書く時は、オブジェクトのアクセスやインデックスの指定に関数 self を使います。
Note, that although the caller specifies the called target object of the call, the method definition does not include the object as a parameter. When writing functions to modify FOOP objects, instead the function self is used to access and index the object.


Structuring a larger FOOP program(大規模 FOOP プログラムの構造化)

前述の例全てにおいて、クラス関数は MAIN コンテキスト名前空間に直接書かれたメソッドです。 これでも動作しますし、一人のプログラマによる小規模のプログラムにとっては十分です。 大規模なシステムを書く時は、使用されるパラメータ変数の独立を保ち、潜在的クラス変数用の隔離場所を作っておくために、一クラスの全メソッドを context 宣言文で囲むべきです。
In all the previous examples, class function methods where directly written into the MAIN context namespace. This works and is adequate for smaller programs written by just one programmer. When writing larger systems, all the methods for one class should be surrounded by context statements to provide better isolation of parameter variables used and to create an isolated location for potential class variables.

この場合、クラス変数を特定のオブジェクト用ではなく、オブジェクトやカウンタやクラスに固有なその他の情報のリスト用の入れ物として使います。 次のコードは、上記例をこの状況用に書き直しています。
Class variables could be used in this example as a container for lists of objects, counters or other information specific to a class but not to a specific object. The following code segment rewrites the example from above in this fashion.

各コンテキスト/名前空間は、クラスと同名の個別のファイルに入れておきます。 クラス生成、開始コード、主制御コードは、ファイル MAIN.lsp にあります:
Each context / namespace could go into an extra file with the same name as the class contained. Class creation, startup code and the main control code is in a file MAIN.lsp:

; file MAIN.lsp - declare all classes used in MAIN

(new Class 'Rectangle)
(new Class 'Circle)

; start up code

(load "Rectangle.lsp")
(load "Circle.lsp")

; main control code

; end of file

各クラスは独立したファイルの中にあります:
Each class is in a separate file:

; file Rectangle.lsp - class methods for rectangles

(context Rectangle)

(define (Rectangle:area)
(mul (self 3) (self 4)))

(define (Rectangle:move dx dy)
(inc (self 1) dx) 
(inc (self 2) dy))

; end of file

そして Circle クラスのファイルは次にようになっています:
And the Circle class file follows:

; file Circle.lsp - class methods for circles

(context Circle)

(define (Circle:area)
    (mul (pow (self 3) 2) (acos 0) 2))

(define (Circle:move dx dy)
    (inc (self 1) dx) 
    (inc (self 2) dy))

; end of file

これでクラス関数の全設定がレキシカルに他から分離されます。
All sets of class functions are now lexically separated from each other.


§ )

19. Concurrent processing and distributed computing(並列処理と分散コンピューティング)

newLISP は、同じ CPU または TCP/IP ネットワーク上の異なるコンピュータ・ノードに分散されるマルチ・プロセス制御用の高レベル API を持っています。
newLISP has high-level APIs to control multiple processes on the same CPU or distributed onto different computer nodes on a TCP/IP network.


Cilk API(Cilk API)

newLISP は並列処理を起動し制御する Cilk 似の API を実装しています。 この API はマルチコア・コンピュータ構成の利点を活かせます。 マルチ・プロセスを開始して、同期状態における結果を収集するために必要なのは、関数 spawnsyncabort の三つだけです。 基盤となるオペレーティングシステムが、プロセスを CPU 内の異なるコアに分配するか、十分なコアがない場合は同一コアで並列に実行させます。 newLISP は API を実装しているだけなので、子プロセスとして呼び出された手続きのスケジュール最適化が Cilk のように実施されるわけではないことに注意してください。 関数は spawn 宣言文に現れた順に開始され、オペレーティングシステムによって、 CPU の異なるコアに分配され、スケジュールされます。
newLISP implements a Cilk- like API to launch and control concurrent processes. The API can take advantage of multi-core computer architectures. Only three functions, spawn, sync and abort, are necessary to start multiple processes and collect the results in a synchronized fashion. The underlying operating system distributes processes onto different cores inside the CPU or executes them on the same core in parallel if there are not enough cores present. Note that newLISP only implements the API; optimized scheduling of spawned procedures is not performed as in Cilk. Functions are started in the order they appear in spawn statements and are distributed and scheduled onto different cores in the CPU by the operating system.

マルチコアの存在は関数を並列に実行することにより、全体的な処理速度向上を可能にします。 とは言え、シングルコア CPU での走行中でもプログラマにとっては、 Cilk API がより簡単な並列処理化を可能にし、I/O やスリープの待ち状態を含むタスクが存在する時には、処理速度を上げられる可能性があります。
When multiple cores are present, this can increase overall processing speed by evaluating functions in parallel. But even when running on single core CPUs, the Cilk API makes concurrent processing much easier for the programmer and may speed up processing if subtasks include waiting for I/O or sleeping.

バージョン 10.1 以降、メッセージ関数 sendreceive はプロセスの親子間通信に利用可能です。 これらの関数はブロッキングとノン・ブロッキング通信に使うことができ、newLISP のいかなる種類のデータや式でも転送できます。 送信された式は受け取り側の環境で評価可能です。
Since version 10.1 send and receive message functions are available for communications between parent and child processes. The functions can be used in blocking and non blocking communications and can transfer any kind of newLISP data or expressions. Transmitted expressions can be evaluated in the recipients environment.

newLISP は内部的に、プロセスや計算結果の共有メモリを通した受け渡しの同期を制御するロー・レベル関数 forkwait-piddestroyshare を使います。
Internally, newLISP uses the lower level fork, wait-pid, destroy, and share functionalities to control processes and synchronize the passing of computed results via a shared memory interface.

Cilk API は macOS や他の Unix 上でのみ、タスクを並列化します。 MS Windows では、この API は 利用できません。 この方法により、全てのプラットフォームで走るコードを書く事ができます。
Only on macOS and other Unixes will the Cilk API parallelize tasks. On MS Windows, the API is not available.


Distributed network computing(分散ネットワーク コンピューティング)

newLISP は net-eval の一関数だけを使って、分散コンピューティングを実装しています。 net-eval を使えば、TCP/IP ネットワーク上のなるノード、または同じコンピュータで走っているローカル・ドメイン Unix ソケット上の異なるノードに、別個のタスクが配され、評価されます。 net-eval はリモート・ノードの接続、実行関数の転送、結果の収集などの全要求リクエストをこなします。 net-eval では、リモート・ノードからのデータ入力を構造的に統合するコール・バック関数も使えます。
With only one function, net-eval, newLISP implements distributed computing. Using net-eval, different tasks can be mapped and evaluated on different nodes running on a TCP/IP network or local domain Unix sockets network when running on the same computer. net-eval does all the housekeeping required to connect to remote nodes, transfer functions to execute, and collect the results. net-eval can also use a call-back function to further structure consolidation of incoming results from remote nodes.

関数 read-filewrite-fileappend-filedelete-file は全て、 パス・ファイル名の代わりに URL を取ることができます。 デーモン・モードで走っている newLISP のサーバー側や Apache のような他の HTTP サーバーでは、標準 HTTP 要求リクエストを受け取り、ファイルに対応する操作を行います。
The functions read-file, write-file, append-file and delete-file all can take URLs instead of path-file names. Server side newLISP running in demon mode or an other HTTP server like Apache, receive standard HTTP requests and translate them into the corresponding actions on files.


§ )

20. JSON, XML, S-XML, and XML-RPC(JSON、XML、SXML と XML-RPC)

JSON support(JSON 支援)

関数 json-parse を使って JSON エンコード・データをS式に変換できます。 JSON の変換に失敗した情報は json-error を使って引き出せます。
JSON-encoded data can be parsed into S-expressions using the json-parse function. Error information for failed JSON translations can be retrieved using json-error.

JSON 形式 (JavaScript Object Notation) の詳細は json.org で調べてください。 正しい JSON 形式のテキストは json.org/examples.html で見ることができます。
For a description of the JSON format (JavaScript Object Notation) consult json.org. Examples for correct formatted JSON text can be seen at json.org/examples.html.

JSON 変換で得られる入れ子リストからデータを取り出すには、関数 assoclookupref を使ってください。
To retrieve data in nested lists resulting from JSON translation, use the assoc, lookup and ref functions.

JSON データの変換と処理の全例は json-parse の項を見てください。
See the description of json-parse for a complete example of parsing and processing JSON data.

XML support(XML 支援)

XML-エンコード・データまたはドキュメントの newLISP の組込サポートは、三つの関数: xml-parsexml-type-tagsxml-error からなります。
newLISP's built-in support for XML-encoded data or documents comprises three functions: xml-parse, xml-type-tags, and xml-error.

XML-エンコード文字列を解析するには、関数 xml-parse を使ってください。 xml-parse がエラーに出会った時は、nil が返ります。 正しくない形式の XML によって起こった構文エラーを診断するには、関数 xml-error を使ってください。 関数 xml-type-tags は XML タイプ・タグの出現を制御または抑制するのに使えます。 これらのタグは XML を四つのカテゴリ:テキスト、生の文字列データ、コメント、エレメント・データの中の一つに分類分けします。
Use the xml-parse function to parse XML-encoded strings. When xml-parse encounters an error, nil is returned. To diagnose syntax errors caused by incorrectly formatted XML, use the function xml-error. The xml-type-tags function can be used to control or suppress the appearance of XML type tags. These tags classify XML into one of four categories: text, raw string data, comments, and element data.

XML source:
<?xml version="1.0"?>
<DATABASE name="example.xml">
<!--This is a database of fruits-->
<FRUIT>
<NAME>apple</NAME>
<COLOR>red</COLOR>
<PRICE>0.80</PRICE>
</FRUIT>
</DATABASE>

Parsing without options:
(xml-parse (read-file "example.xml"))
  (("ELEMENT" "DATABASE" (("name" "example.xml")) (("TEXT" "\r\n")
("COMMENT" "This is a database of fruits")
("TEXT" "\r\n        ")
("ELEMENT" "FRUIT" () (
	("TEXT" "\r\n\t        ")
	("ELEMENT" "NAME" () (("TEXT" "apple")))
	("TEXT" "\r\n\t\t")
	("ELEMENT" "COLOR" () (("TEXT" "red")))
	("TEXT" "\r\n\t\t")
	("ELEMENT" "PRICE" () (("TEXT" "0.80")))
	("TEXT" "\r\n\t")))
("TEXT" "\r\n"))))

関数 xml-type-tagsxml-parse の特殊オプション・パラメータを使って、XML から直接 S-XML を生成できます:
S-XML can be generated directly from XML using xml-type-tags and the special option parameters of the xml-parse function:


S-XML generation using all options:
(xml-type-tags nil nil nil nil)
(xml-parse (read-file "example.xml") (+ 1 2 4 8 16))
  ((DATABASE (@ (name "example.xml"))
  (FRUIT (NAME "apple")
	  (COLOR "red")
	  (PRICE "0.80"))))
	

S-XML は newLISP のS式 として再構成された XML です。 @ (at symbol) は XML の属性詳細を付与します。
S-XML is XML reformatted as newLISP S-expressions. The @ (at symbol) denotes an XML attribute specification.

S-XML 変換で得られる入れ子リストからデータを取り出すには、関数 assoclookupref を使ってください。
To retrieve data in nested lists resulting from S-XML translation, use the assoc, lookup and ref functions.

マニュアルのリファレンス項にある xml-parse を見てください。解析とオプション番号の詳細について、より長い例があります。
See xml-parse in the reference section of the manual for details on parsing and option numbers, as well as for a longer example.


XML-RPC

XML-RPC プロトコルを呼び出すリモート手続きは、転送とメソッド名、パラメータ、パラメータ・タイプをエンコードする XML に HTTP ポスト要求リクエストを使います。 XML-RPC クライアントのライブラリとサーバーは、最も一般的なコンパイルされたスクリプト言語で実装されています。
The remote procedure calling protocol XML-RPC uses HTTP post requests as a transport and XML for the encoding of method names, parameters, and parameter types. XML-RPC client libraries and servers have been implemented for most popular compiled and scripting languages.

XML についての詳しい情報は www.xmlrpc.com を訪れて見てください。
For more information about XML, visit www.xmlrpc.com.

XML-RPC クライアントのライブラリとサーバーは、newLISP の組込ネットーワークと XML サポートを使って容易に書けます。 CGI サービスとして実装された非公式(stateless)XML-RPC サーバーは、ファイル examples/xmlrpc.cgi に見つかります。 このスクリプトを Apache のようなウェブ・サーバーとしても使うことができます。 この XML-RPC サーバー・スクリプトは次のメソッドを実装します:
XML-RPC clients and servers are easy to write using newLISP's built-in network and XML support. A stateless XML-RPC server implemented as a CGI service can be found in the file examples/xmlrpc.cgi. This script can be used together with a web server, like Apache. This XML-RPC service script implements the following methods:

methoddescription
system.listMethods 全てのメソッド名を返す
Returns a list of all method names
system.methodHelp 特定のメソッドのヘルプを返す
Returns help for a specific method
system.methodSignature 特定のメソッドのリターン/署名の呼び出しのリストを返す
Returns a list of return/calling signatures for a specific method
newLISP.evalString Base64(訳注:でエンコードされた)newLISP 式の文字列を評価する
Evaluates a Base64 newLISP expression string

最初の三つは、ほとんどの XML-RPC サーバーで実装されたメソッドとして見つかります 。 最後の一つは newLISP の XML-RPC サーバー・スクリプトに特有のもので、newLISP ソース・コードの Base64 エンコード文字列のリモート評価を実装します。 newLISP の関数 base64-encbase64-dec を Base64 エンコード情報のエンコードとデコードに使えます。
The first three methods are discovery methods implemented by most XML-RPC servers. The last one is specific to the newLISP XML-RPC server script and implements remote evaluation of a Base64-encoded string of newLISP source code. newLISP's base64-enc and base64-dec functions can be used to encode and decode Base64-encoded information.

配布ソースの modules ディレクトリにあるファイル xmlrpc-client.lsp は、上記メソッド全てについての具体的なクライアント・インターフェイスを実装しています。
In the modules directory of the source distribution, the file xmlrpc-client.lsp implements a specific client interface for all of the above methods.

(load "xmlrpc-client.lsp")  ; load XML-RPC client routines						 

(XMLRPC:newLISP.evalString
"http://localhost:8080/xmlrpc.cgi"
"(+ 3 4)")   "7"

同様に、標準 system.xxx 呼出しを発行できます。
In a similar fashion, standard system.xxx calls can be issued.

すべての関数は成功なら結果を、要求リクエストが失敗なら nil を返します。 失敗の場合、(XMLRPC:error) の式を評価すればエラー・メッセージが返ります。
All functions return either a result if successful, or nil if a request fails. In case of failure, the expression (XMLRPC:error) can be evaluated to return an error message.

詳細な情報は、どうかをファイル modules/xmlrpc-client.lsp のヘッダーを調べて見てください。
For more information, please consult the header of the file modules/xmlrpc-client.lsp.


§ )

21. Customization, localization, and UTF-8(カスタマイズ、ローカライズと UTF-8)

Customizing function names(関数名のカスタマイズ)

newLISP では、全ての組込関数を簡単にリネームできます:
All built-in primitives in newLISP can be easily renamed:

(constant 'plus +)

これで、plus は関数として + に評価され、同じスピードで走ります。
Now, plus is functionally equivalent to + and runs at the same speed.

組込関数シンボルのリネームには、関数 set よりも関数 constant を使うべきです。 全組込関数シンボルは、デフォルトで不慮の上書きに対して保護されています。
The constant function, rather than the set function, must be used to rename built-in primitive symbols. By default, all built-in function symbols are protected against accidental overwriting.

全ての整数算術演算子を浮動小数点同等品に再定義することが可能です:
It is possible to redefine all integer arithmetic operators to their floating point equivalents:

(constant '+ add)
(constant '- sub)
(constant '* mul)
(constant '/ div)

これで、+, -, *, / を使った全ての操作が、浮動小数点演算として実行されます。
All operations using +, -, *, and / are now performed as floating point operations.

同じ方法で、組込関数名を英語以外の言語にも変換できます:
Using the same mechanism, the names of built-in functions can be translated into languages other than English:

(constant 'wurzel sqrt)    ; German for 'square-root'

; make the new symbol global at the same time
(constant (global 'imprime) print)  ; Spanish for 'print'
…

同時に global を使うことで、新関数を(訳注:どのコンテキストからも使える)グローバルにできます。
The new symbol can be made global at the same time using global.


Switching the locale(ロケールの切り替え)

newLISP は、プラットフォームやオペレーティングシステムに基づくロケールを切り替えることができます。 開始時に、UTF-8版でない newLISP は、ほとんどのプラットフォームやロケールで利用可能な POSIX ロケールのデフォルト、ISO C 標準 の設定を試みます。 UTF-8版 newLISP では、プラットフォームのデフォルト・ロケールに設定します。 デフォルトのロケールを切り替えるのに、関数 set-locale を使えます:
newLISP can switch locales based on the platform and operating system. On startup, non-UTF-8 enabled newLISP attempts to set the ISO C standard default POSIX locale, available for most platforms and locales. On UTF-8 enabled newLISP the default locale for the platform is set. The set-locale function can also be used to switch to the default locale:

(set-locale "")

これは、あなたのプラットフォーム/オペレーティングシステムで使われているデフォルトのロケールに切り替え、文字操作(例えば、upper-case)の正しい動作を保証します。
This switches to the default locale used on your platform/operating system and ensures character handling (e.g., upper-case) works correctly.

多くの Unix システムは、多数の利用可能なロケールを持っています。 個々の Linux/Unix/BSD システムで利用可能な一つを見つけるには、システム・シェルで次のコマンドを実行してください:
Many Unix systems have a variety of locales available. To find out which ones are available on a particular Linux/Unix/BSD system, execute the following command in a system shell:

locale -a

このコマンドは、あなたのシステムで利用可能な全ロケールのリストを表示します。 それらのどれもが set-locale の引数に使えます:
This command prints a list of all the locales available on your system. Any of these may be used as arguments to set-locale:

(set-locale "es_US")

これは、U.S. Spanish ロケールに切り替えます。 U.S. Spanish 環境で使えるアクセントや文字が正しく変換されます。
This would switch to a U.S. Spanish locale. Accents or other characters used in a U.S. Spanish environment would be correctly converted.

詳細は、set-locale の使い方のマニュアルの記述を見てください。
See the manual description for more details on the usage of set-locale.


Decimal point and decimal comma(十進点と十進カンマ)

多くの国々が十進数の区切りにピリオドでなくカンマを使っています。 newLISP はロケールの設定次第で正しく数値を解析します:
Many countries use a comma instead of a period as a decimal separator in numbers. newLISP correctly parses numbers depending on the locale set:

; switch to German locale on a Linux  or OSX system
(set-locale "de_DE")  ("de_DE" ",")

; newLISP source and output use a decimal comma
(div 1,2 3)   0,4

newLISP 開始時に設定されるデフォルトの POSIX C ロケールは、十進数の区切りにピリオドを使います。 uses a period as a decimal separator.
The default POSIX C locale, which is set when newLISP starts up, uses a period as a decimal separator.

次の国々は 十進数の区切りにピリオドを使います:
The following countries use a period as a decimal separator:

Australia, Botswana, Canada (English-speaking), China, Costa Rica, Dominican Republic, El Salvador, Guatemala, Honduras, Hong Kong, India, Ireland, Israel, Japan, Korea (both North and South), Malaysia, Mexico, Nicaragua, New Zealand, Panama, Philippines, Puerto Rico, Saudi Arabia, Singapore, Switzerland, Thailand, United Kingdom, and United States.

次の国々は 十進数の区切りにカンマを使います:
The following countries use a comma as a decimal separator:

Albania, Andorra, Argentina, Austria, Belarus, Belgium, Bolivia, Brazil, Bulgaria, Canada (French-speaking), Croatia, Cuba, Chile, Colombia, Czech Republic, Denmark, Ecuador, Estonia, Faroes, Finland, France, Germany, Greece, Greenland, Hungary, Indonesia, Iceland, Italy, Latvia, Lithuania, Luxembourg, Macedonia, Moldova, Netherlands, Norway, Paraguay, Peru, Poland, Portugal, Romania, Russia, Serbia, Slovakia, Slovenia, Spain, South Africa, Sweden, Ukraine, Uruguay, Venezuela, and Zimbabwe.

Unicode and UTF-8 encoding(Unicode と UTF-8 エンコーディング)

多くのヨーロッパ言語では、内部的に各文字が一バイト で表示されている限り、非 ASCII 文字セットを表示するのに set-locale 機構で十分であることに注意してください。 この章で記述されるマルチ・バイト文字セット用にのみ、UTF-8 エンコードが必要となります。
Note that for many European languages, the set-locale mechanism is sufficient to display non-ASCII character sets, as long as each character is presented as one byte internally. UTF-8 encoding is only necessary for multi-byte character sets as described in this chapter.

newLISP を UTF-8版アプリケーションとしてコンパイルできます。 UTF-8 は国際 Unicode 文字セットのマルチ・バイト・エンコーディングです。 UTF-8 利用可能なオペレーティングシステムで走っている UTF-8 版 newLISP は、導入されるロケールの文字セットを処理できます。
newLISP can be compiled as a UTF-8–enabled application. UTF-8 is a multi-byte encoding of the international Unicode character set. A UTF-8–enabled newLISP running on an operating system with UTF-8 enabled can handle any character of the installed locale.

次のステップは、特定のオペレーティングシステムやプラットフォームで、UTF-8 版 newLISP を作成します:
The following steps make UTF-8 work with newLISP on a specific operating system and platform:

(1) newLISP を UTF-8 アプリケーションとしてコンパイルするために、utf8 で終わっている makefile の一つを使ってください。 あなたのプラットフォームで利用可能な UTF-8 makefile がないならば、あなたのプラットフォーム用の一般 makefile に UTF-8 用に変えるための指示が入っています。
  Use one of the makefiles ending in utf8 to compile newLISP as a UTF-8 application. If no UTF-8 makefile is available for your platform, the normal makefile for your operating system contains instructions on how to change it for UTF-8.

macOS バイナリ・インストーラには、デフォルトで UTF-8 版が入っています。
The macOS binary installer contains a UTF-8–enabled version by default.

(2) あなたのプラットフォームで、UTF-8 ロケールを許可してください。 Unix や Unix-like OS 上の locale コマンドか newLISP の関数 set-locale を使って、UTF-8 ロケールのチェックと設定をしてください。 Linux では、適切な環境変数を設定することでロケールを変更できます。 次の例は、U.S. ロケールの設定に bash を使っています:
  Enable the UTF-8 locale on your operating system. Check and set a UTF-8 locale on Unix and Unix-like OSes by using the locale command or the set-locale function within newLISP. On Linux, the locale can be changed by setting the appropriate environment variable. The following example uses bash to set the U.S. locale:

export LC_CTYPE=en_US.UTF-8

(3) UTF-8 版 newLISP はオペレーティングシステムで見つかったロケールに自動的に切り替えます。 コマンド・シェルを確実に UTF-8 可能にしてください。 U.S. 版 WinXP の notepad.exe はユニコード UTF-8 エンコード文字を表示可能ですが、コマンド・シェルはそれを表示できません。 Linux や他の Unix では、Xterm シェルの開始時、次のようにすれば可能です:
  The UTF-8–enabled newLISP automatically switches to the locale found on the operating system. Make sure the command shell is UTF-8–enabled. The U.S. version of WinXP's notepad.exe can display Unicode UTF-8–encoded characters, but the command shell cannot. On Linux and other Unixes, the Xterm shell can be used when started as follows:

LC_CTYPE=en_US.UTF-8 xterm

次の手続きを UTF-8 サポートのチェックに使えます。 newLISP を開始した後、次をタイプすると:
The following procedure can now be used to check for UTF-8 support. After starting newLISP, type:

(println (char 937))               ; displays Greek uppercase omega
(println (lower-case (char 937)))  ; displays lowercase omega

ラテン・アルファベットでは、大文字のオメガ (Ω) が二つの小さい足の上に大きいOのように見えている時、小文字のオメガ (ω) は小文字の w に似た形状を持ちます。
While the uppercase omega (Ω) looks like a big O on two tiny legs, the lowercase omega (ω) has a shape similar to a small w in the Latin alphabet.

注記:println の出力の時だけ、文字として表示されます。 println の戻り値は、マルチ・バイト ASCII 文字としてコンソールに現れます。
Note: Only the output of println will be displayed as a character; println's return value will appear on the console as a multi-byte ASCII character.

UTF-8 を表示できない環境でも UTF-8 版 newLISP を使え、出力と戻り値の両方が2文字になります。 オメガ文字をエンコードするのに2バイト必要です。
When UTF-8–enabled newLISP is used on a non-UTF-8–enabled display, both the output and the return value will be two characters. These are the two bytes necessary to encode the omega character.


Functions working on UTF-8 characters(UTF-8 文字で動作する関数)

UTF-8 版 newLISP が使える時、次の文字列関数は 8ビットの1バイト文字上ではなく、1バイトもしくはマルチ・バイト文字上で動作します(訳注:バイト単位でなく、文字単位で動作します):
When UTF-8–enabled newLISP is used, the following string functions work on one- or multi-byte characters rather than one 8-bit byte boundaries:

functiondescription
char 文字と ASCII/Unicode 間の変換をする
translates between characters and ASCII/Unicode
chop 文字列の最後から文字を削除する
chops characters from the end of a string
date (第三引数と共に使って)日付数値を文字列に変換する
converts date number to string (when used with the third argument)
dostring 文字列の各文字列で一回ずつ評価する
evaluates once for each character in a string
explode 文字列を文字のリストに変換する
transforms a string into a list of characters
first リスト (car, head) か文字列の第一要素を取得する
gets first element in a list (car, head) or string
last リストか文字列の最後の要素を取得する
returns the last element of a list or string
lower-case 文字列を小文字に変換する
converts a string to lowercase characters
nth リストか文字列のn番目の要素を取得する
gets the nth element of a list or string
pop リストや文字列から要素を削除する
deletes an element from a list or string
push リストや文字列に新しい要素を挿入する
inserts a new element in a list or string
rest リスト (cdr, tail) か文字列の第一要素以外の全てを取得する
gets all but the first element of a list (cdr, tail) or string
select リストか文字列から要素を選んで並べ換える
selects and permutes elements from a list or string
title-case 文字列の第一文字を大文字に変換する
converts the first character of a string to uppercase
trim 文字列の両端からトリム(訳注:空白文字を削除)する
trims a string from both sides
upper-case 文字列を大文字に変換する
converts a string to uppercase characters

他の文字列関数は全て、8ビット・バイト上で動作します。 findregex で返る位置は、マルチ・バイトの文字位置ではなく、1バイト単位の位置です。 関数 get-charslice は、UTF-8 版 newLISP であってもマルチ・バイト文字のオフセットを取らず、1バイト単位のオフセットになります。 関数 reverse は文字ベクターではなくバイト・ベクターで逆転します。 UTF-8 版 newLISP で、最後の三つの関数(訳注:get-charslicereverse )にできるのは、バイナリの非テキストデータ操作です。 UTF-8 文字列で動作する slicereverse を作成するには、explodejoin を組み合わせます。
All other string functions work on 8-bit bytes. When positions are returned, as in find or regex, they are single 8-bit byte positions rather than character positions which may be multi-byte. The get-char and slice functions do not take multi-byte character offsets, but single-byte offsets, even in UTF-8 enabled versions of newLISP. The reverse function reverses a byte vector, not a character vector. The last three functions can still be used to manipulate binary non-textual data in the UTF-8–enabled version of newLISP. To make slice and reverse work with UTF-8 strings, combine them with explode and join.

directoryfindmemberparseregexregex-compreplace で使われる—Perl Compatible Regular Expressions (PCRE) で UTF-8 利用する際は、適宜オプション番号 (2048) を設定してください。 regex の結果のオフセットと長さは、常に1バイト単位のカウントであることに注意してください。 詳細は、regex の項を見てください。
To enable UTF-8 in Perl Compatible Regular Expressions (PCRE) — used by directory, find, member, parse, regex, regex-comp and replace — set the option number accordingly (2048). Note that offset and lengths in regex results are always in single byte counts. See the regex documentation for details.

UTF-8 を操作できない関数関数で UTF-8 文字列のアレイを入手したり、バイトではなく文字を操作したい時は、explode を使ってください
Use explode to obtain an array of UTF-8 characters and to manipulate characters rather than bytes when a UTF-8–enabled function is unavailable:

(join (reverse (explode str)))  ; reverse UTF-8 characters

こうすれば、上記(非テキストのバイナリ・データの操作によく使われる)文字列関数がバイト境界ではなく文字境界で動作します。このように、UTF-8 バージョンを使う時は注意が必要です。 ISO 8859 のような一般的なコード・ページでは、ASCII 文字の最初の 127 個は1バイト長です。 このようなコード・ページでのみ動かすなら、UTF-8 版 newLISP は必要ありません。 動作をローカル化するための関数 set-locale で十分です。
The above string functions (often used to manipulate non-textual binary data) now work on character, rather than byte, boundaries, so care must be exercised when using the UTF-8–enabled version. The size of the first 127 ASCII characters — along with the characters in popular code pages such as ISO 8859 — is one byte long. When working exclusively within these code pages, UTF-8–enabled newLISP is not required. The set-locale function alone is sufficient for localized behavior.


Functions only available on UTF-8 enabled versions(UTF-8 バージョンでのみ利用できる関数)

functiondescription
unicode UTF-8 文字列や ASCII 文字列を USC-4 ユニコードに変換する
converts UTF-8 or ASCII strings into USC-4 Unicode
utf8 USC-4 ユニコード文字列を UTF-8 に変換する
converts UCS-4 Unicode strings to UTF-8
utf8len 文字列の UTF-8 文字数を返す
returns the number of UTF-8 characters in a string

ほとんどの Unicode テキストは、すでに(4バイト文字を使う UCS-4 よりはむしろ)UTF-8 エンコードされているので、最初の二つの関数が実際に使われることは、めったにありません。 format"%ls" 指定子を使って、Unicode を直接表示できます。
The first two functions are rarely used in practice, as most Unicode text files are already UTF-8–encoded (rather than UCS-4, which uses four-byte integer characters). Unicode can be displayed directly when using the "%ls" format specifier.

UTF-8 と Unicode のさらなる詳細については、Markus Kuhn による UTF-8 and Unicode FAQ for Unix/Linux を調べてみてください。
For further details on UTF-8 and Unicode, consult UTF-8 and Unicode FAQ for Unix/Linux by Markus Kuhn.


§ )

22. Commas in parameter lists(パラメータ リストのカンマ)

例題プログラムの中には、パラメータを二つのグループに分けるカンマを使っている関数があります。 これは newLISP の特殊構文でなく、どちらかというと視覚的トリックです。 カンマは他のシンボルと同様に単なるシンボルです。 関数が呼ばれた時、カンマ以降のパラメータが必要とされておらず(訳注:必要とされないように関数が書かれているという意味)、単にローカル変数として簡易的な方法で宣言されているだけです。 これが newLISP で可能なのは、ラムダ式内のパラメータ変数がローカルになり、引数はオプションになるためです:
Some of the example programs contain functions that use a comma to separate the parameters into two groups. This is not a special syntax of newLISP, but rather a visual trick. The comma is a symbol just like any other symbol. The parameters after the comma are not required when calling the function; they simply declare local variables in a convenient way. This is possible in newLISP because parameter variables in lambda expressions are local and arguments are optional:

(define (my-func a b c , x y z)
    (set 'x …)
(…))

この関数が呼ばれた時、abc だけがパラメータとして使われます。 他 (x, y, z) は nil で初期化され、関数のローカル変数になります。 実行後、この関数の内部変数は忘れ去られ、環境に存在したシンボルの値は、以前の値に戻ります。
When calling this function, only a, b, and c are used as parameters. The others (the comma symbol, x, y, and z) are initialized to nil and are local to the function. After execution, the function's contents are forgotten and the environment's symbols are restored to their previous values.

ローカル変数を宣言し、初期化する他の方法については letletexletn を見てください。
For other ways of declaring and initializing local variables, see let, letex and letn.


§ )




 )

newLISP Function Reference(newLISP 関数リファレンス)



1. Syntax of symbol variables and numbers(シンボル変数と数値の構文)

newLISP におけるソース・コードは、ここで概説される規則に従って解析されます。 疑わしい時は、オプションの引数無しで parse を使い、newLISP の内部解析動作を確認してください。
Source code in newLISP is parsed according to the rules outlined here. When in doubt, verify the behavior of newLISP's internal parser by calling parse without optional arguments.


Symbols for variable names(変数名のシンボル)

変数や関数に使われるシンボルの命名には、次の規則が適用されます:
The following rules apply to the naming of symbols used as variables or functions:

  1. 変数シンボルは、次の文字から始まってはならない:
    # ; " ' ( ) { } . , 0 1 2 3 4 5 6 7 8 9
    Variable symbols should not start with any of the following characters:
    # ; " ' ( ) { } . , 0 1 2 3 4 5 6 7 8 9

  2. + または - で始まる変数シンボルは、二文字目に数字を使うことはできない。
    Variable symbols starting with a + or - cannot have a number as the second character.

  3. 変数名の内部にはどんな文字も許されるが、以下の文字は除く:
    " ' ( ) : , 半角スペース。これらは、変数シンボルの終りを意味する。
    Any character is allowed inside a variable name, except for:
    " ' ( ) : , and the space character. These mark the end of a variable symbol.

  4. [(左角括弧)で始まり ](右角括弧)で終わるシンボルは、右角括弧を除くどんな文字を含んでもよい。
    A symbol name starting with [ (left square bracket) and ending with ] (right square bracket) may contain any character except the right square bracket.

  5. $(ドル記号)で始まるシンボルはグローバルになる。前もって newLISP に組み込まれているものも有り、内部で設定または変更される。この種のグローバル・シンボルをユーザが生成することもできる。
    A symbol name starting with $ (dollar sign) is global. There are several of these symbols already built into newLISP and set and changed internally. This type of global symbol can also be created by the user.

newLISP において、次のシンボルは全て適正なシンボル名です:
All of the following symbols are legal variable names in newLISP:

myvar
A-name
X34-zz
[* 7 5 ()};]
*111*

newLISP の変数としては不適切な文字からなるキーを持つハッシュ似の検索辞書を生成することが、時として有用です。 このような文字を含むシンボルの生成に関数 symcontext が使えます:
Sometimes it is useful to create hash-like lookup dictionaries with keys containing characters that are illegal in newLISP variables. The functions sym and context can be used to create symbols containing these characters:

(set (sym "(#:L*") 456)   456 ; the symbol '(#:L*'

(eval (sym "(#:L*"))   456

(set (sym 1) 123)   123

(eval (sym 1))   123

1         1
(+ 1 2)   3

最後の例は、値 123 を持つシンボル 1 を生成しています。1 は数字の一としても解析される状態のまま残ります。このようなシンボル生成が newLISP の通常操作を変更しないことにも注意が必要です。
The last example creates the symbol 1 containing the value 123. Also note that creating such a symbol does not alter newLISP's normal operations, since 1 is still parsed as the number one.


Numbers(数値)

二進数、十六進数、十進数、浮動小数、整数値の解析において、今のところ 1000 桁までは解析されます。残りは新トークンとして読み込まれます。 注記:IEEE 754 の 64 ビット倍精度で識別できる桁数は高々16桁です。指数部が308以上ならば、その数値は inf(無限大)になります。 大整数においてもソースの解析時には 1000 桁の制限があります。1000桁を超える整数の演算の結果には制限はありません。
When parsing binary, hex, decimal, float and integer numbers, up to 1000 digits are parsed when present. The rest will be read as new token(s). Note that IEEE 754 64-bit doubles distinguish only up to 16 significant digits. If more than 308 digits are present before the decimal point, the number will convert to inf (infinity). For big integers the 1000 limitation exists only when parsing source. There is no limit when a result of big integers math exceeds 1000 digits.

newLISP は次の数値形式を認識します:
newLISP recognizes the following number formats:

整数は一個以上のアラビア数字からなり、オプションで +- の符号が先に付きます。 それ以外の文字は整数の終りを意味します。 浮動小数点として解析される場合は、数値の一部の可能性もあります(下の浮動小数点構文を見てください)。
Integers are one or more digits long, optionally preceded by a + or - sign. Any other character marks the end of the integer or may be part of the sequence if parsed as a float (see float syntax below).

123
+4567
-999

大整数の桁数には制限がなく、通常の 64 ビット整数とは内部処理が異なります。
Big integers can be of unlimited precision and are processed differently from normal 64-bi integers internally.

123456789012345678901234567890 ; will automatically be converted to big int
-123L                          ; appended L forces conversion
0L

newLISP はコマンド・ラインやプログラミング・ソースを解析する際、64ビット整数より大きな数を認識すると、大整数に変換します。 小さい数でも末尾に文字 L を追加することで、強制的に大変数にできます。
when parsing the command line or programming source, newLISP will recognise, integers bigger than 64-bit and convert the to big integers. Smaller numbers can be forced to big integer format by appending the letter L.

十六進数は、0x (または 0X) で始まり、十六進数字 0123456789abcdefABCDEF の組み合わせが続きます。 それ以外の文字は十六進数の終りを意味します。 その際、十六進数までが有効で、それ以上の桁は全て無視されます。
Hexadecimals start with a 0x (or 0X), followed by any combination of the hexadecimal digits: 0123456789abcdefABCDEF. Any other character ends the hexadecimal number. Only up to 16 hexadecimal digits are valid and any more digits are ignored.

0xFF      255
0x10ab   4267
0X10CC   4300

二進数0b (または 0B) で始まり、64個まで 1 か 0 が 続きます。 それ以外の文字は二進数の終わりを意味します。 つまり、どんな文字も二進数の終わりになります。 64 ビットまでが有効でそれ以上のビットは無視されます。
Binaries start with a 0b (or 0B), followed by up to 64 bits coded with 1's or 0s. Any other character ends the binary number. Only up to 64 bits are valid and any more bits are ignored.

0b101010     42

八進数はオプションの + (plus) か - (minus) 符号と 0(ゼロ)から始まり、八進数字 01234567 の組み合わせが続きます。 21 桁までが有効で、それ以上の桁は無視されます。
Octals start with an optional + (plus) or - (minus) sign and a 0 (zero), followed by any combination of the octal digits: 01234567. Any other character ends the octal number. Only up to 21 octal digits are valid and any more digits are ignored.

012     10
010      8
077     63
-077   -63

浮動小数点数はオプションの + (plus) か - (minus) 符号で始められますが、その後に 0 (zero) を続けることはできません。 それでは浮動小数点の代わりに八進数になってしまうからです。 先頭を含む、浮動小数点数中のどこにでも一個の . (小数点) を置けます。
Floating point numbers can start with an optional + (plus) or - (minus) sign, but they cannot be followed by a 0 (zero); this would make them octal numbers instead of floating points. A single . (decimal point) can appear anywhere within a floating point number, including at the beginning.

16 桁までが有効で、それ以上の桁は無視されます。(訳注:16 桁を超える入力はすべきではありません)
Only 16 digits are siginificant and any more digits are ignored.

1.23       1.23
-1.23     -1.23
+2.3456    2.3456
.506       0.506

下記のように、指数表記(または、科学的表記)は仮数部(または仮数 )と呼ばれる浮動小数点数から始まり、eE の文字と整数の指数部 が続きます。
As described below, scientific notation starts with a floating point number called the significand (or mantissa), followed by the letter e or E and an integer exponent.

1.23e3      1230
-1.23E3    -1230
+2.34e-2    0.0234
.506E3      506

§ )

2. Data types and names in the reference(リファレンスでのデータ型と名前)

このリファレンス項での関数パラメータの型と名前の表記には、次の命名則が適用されます:
To describe the types and names of a function's parameters, the following naming convention is used throughout the reference section:

syntax: (format str-format exp-data-1 [exp-data-i ... ])

引数は、引数の型と名前を - (hyphen) で区切った形式で表す。 例えば、 str-format(一個の文字列)と exp-data-1(一個の式)の名前は、それぞれ "format" と "data-1" となる。
Arguments are represented by symbols formed by the argument's type and name, separated by a - (hyphen). Here, str-format (a string) and exp-data-1 (an expression) are named "format" and "data-1", respectively.

角括弧 [] で囲まれた引数はオプションである。 縦線 | で区切られた引数は、その中の一つが選択される。
Arguments enclosed in brackets [ and ] are optional. When arguments are separated by a vertical | then one of them must be chosen.

array

(関数 array で作成される)アレイ。
An array (constructed with the array function).

body

評価するための一個以上の式。 一個より多い式は、連続して評価される。
One or more expressions for evaluation. The expressions are evaluated sequentially if there is more than one.

1 7.8
nil
(+ 3 4)
"Hi" (+ a b)(print result)
(do-this)(do-that) 123

bool

truenil、または、この二つのどちらかに評価される式。
true, nil, or an expression evaluating to one of these two.

true, nil, (<= X 10)

context

コンテキスト(名前空間)に評価される式、または、コンテキストを保持する変数シンボル。
An expression evaluating to a context (namespace) or a variable symbol holding a context.

MyContext, aCtx, TheCTX

exp

この章に表記されているあらゆるデータ型。
Any data type described in this chapter.

func

演算子シンボルかラムダ式に評価されるシンボル、または、式。
A symbol or an expression evaluating to an operator symbol or lambda expression.

+, add, (first '(add sub)), (lambda (x) (+ x x))

int

整数、または、整数に評価される式。 一般に、整数が予想されるところに浮動小数点数が使われた場合、値は整数に切り捨てらる。
An integer or an expression evaluating to an integer. Generally, if a floating point number is used when an int is expected, the value is truncated to an integer.

123, 5, (* X 5)

list

(あらゆる型の)要素のリスト、または、リストに評価される式。
A list of elements (any type) or an expression evaluating to a list.

(a b c "hello" (+ 3 4))

num

整数か浮動小数点数、または、このどちらかに評価される式。 整数が渡された場合は、浮動小数点数に変換される。
An integer, a floating point number, or an expression evaluating to one of these two. If an integer is passed, it is converted to a floating point number.

1.234, (div 10 3), (sin 1)

matrix

各行の要素がリストのリスト、または、各行の要素がアレイのアレイ。 全ての(行の)要素リストまたはアレイは、同じ長さである。 どのようなような型も行列の要素にできるが、 detmultiplyinvert のような行列専用操作を使う時は、全ての数値が浮動小数点数か整数でなければならない。
A list in which each row element is itself a list or an array in which each row element is itself an array. All element lists or arrays (rows) are of the same length. Any data type can be element of a matrix, but when using specific matrix operations like det, multiply, or invert, all numbers must be floats or integers.

行列の次元は、行の数と行当たりの列の数を指し示すことで定義される。 行列で動作する関数は、行中の余計な列を無視する。 見つからない行の要素には、 関数detmultiplyinvert では 0.0 が割り当てられ、 transpose では nil が割り当てられる。 行がリストやアレイでなく、何か他のデータ型の時、transpose には特殊規則が適用される。
The dimensions of a matrix are defined by indicating the number of rows and the number of column elements per row. Functions working on matrices ignore superfluous columns in a row. For missing row elements, 0.0 is assumed by the functions det, multiply, and invert, while transpose assumes nil. Special rules apply for transpose when a whole row is not a list or an array, but some other data type.

((1  2  3  4)
(5  6  7  8)
(9 10 11 12))        ; 3 rows 4 columns
		   
((1 2) (3 4) (5 6))  ; 3 rows 2 columns

place

シンボルによって参照される位置、または、リストやアレイで定義される位置、または、nth暗黙の要素指定 で 指し示される文字列、または、 firstlastassoclookup のような関数で参照される位置。
A place referenced by a symbol or a place defined in a list, array or string by indexing with nth or implicit indexing or a place referenced by functions like first, last, assoc or lookup.

str

文字列、または、文字列に評価される式。
A string or an expression that evaluates to a string.

文字列は長さや特殊文字の処理により範囲が決まります。クォート "" や括弧 {}[text][/text] タグ によってです。
Depending on the length and processing of special characters, strings are delimited by either quotes "", braces {} or [text][/text] tags.

クォート "" や括弧 {} でくくる文字列は 2047 文字を超えてはいけません。それより長い文字列には長さ制限のない文字列をくくれる [text][/text] タグを使うべきです。
Strings limited by either quotes "" or braces {} must not exceed 2047 characters. Longer strings should be limited by [text][/text] tags for unlimited text length.

"Hello", (append first-name  " Miller")

特殊文字は、キャラクタか数字の前にエスケープを示す \ (バックスラッシュ、訳注:日本語環境では円記号 ¥ ) を置くことでクォートされた文字内に含めることが可能:
Special characters can be included in quoted strings by placing a \ (backslash) before the character or digits to escape them:

characterdescription
\"ダブル・クォートで囲まれた文字列内のダブル・クォート
for a double quote inside a quoted string
\nライン・フィード文字 (ASCII 10)
the line-feed character (ASCII 10)
\rキャリッジ・リターン文字 (ASCII 13)
the carriage return character (ASCII 13)
\bバックスペース文字 (ASCII 8)
for a backspace BS character (ASCII 8)
\tタブ文字 (ASCII 9)
the tab character (ASCII 9)
\fフォームフィード文字 (ASCII 12)
for a formfeed FF character (ASCII 12)
\nnn十進数のアスキー・コードで、nnn は 000 から 255 です
a decimal ASCII code where nnn is between 000 and 255
\xnn十六進数コードで、nn は 00 から FF です
a hexadecimal code where nn is between 00 and FF
\unnnn4 つの nnnn 十六進数にエンコードされたユニコード文字。UTF-8 版 newLISP がクォートされた文字列を読みる時は、UTF8 文字に翻訳する。
a unicode character encoded in the four nnnn hexadecimal digits. When reading a quoted string, newLISP will translate this to a UTF8 character in the UTF8 enabled versions of newLISP.
\\バックスラッシュ文字(訳注:日本語環境では円記号 ¥ )自体
the backslash character itself

十進数は数字で始まる。十六進数は xで始まる:
Decimals start with a digit. Hexadecimals start with x:

"\065\066\067"  "ABC"
"\x41\x42\x43"  "ABC"

" (double quote) の代わりに、{ (左波括弧) と } (右波括弧) が文字列を囲むのに使える。 これは、引用マークが文字列内に必要な時、役に立つ。 波括弧による引用は、特殊文字用のバックスラッシュのエスケープ効果を抑制する。 対応が取れている波括弧も文字列における場合もある。 これは、正規表現や HTML の短い部品を書く時の助けになる。
Instead of a " (double quote), a { (left curly bracket) and } (right curly bracket) can be used to delimit strings. This is useful when quotation marks need to occur inside strings. Quoting with the curly brackets suppresses the backslash escape effect for special characters. Balanced nested curly brackets may be used within a string. This aids in writing regular expressions or short sections of HTML.

(print "<a href=\"http://mysite.com\">" ) ; the cryptic way

(print {<a href="http://mysite.com">} )   ; the readable way


; path names on MS Windows

(set 'path "C:\\MyDir\\example.lsp")

; no escaping when using braces

(set 'path {C:\MyDir\example.lsp})

; on MS Windows the forward slash can be used in path names

(set 'path "C:/MyDir/example.lsp")

; inner braces are balanced
(regex {abc{1,2}} line) 

(print [text]
  this could be
  a very long (> 2048 characters) text,
  i.e. HTML.
[/text])

[text][/text] のタグは、長い文字列を囲みたい時やエスケープ文字翻訳を抑圧したい時に使える。 これは、newLISP で書かれた CGI ファイルの HTML 節を囲見たい時や文字変換を完全に抑圧したい時に役立つ。 2048文字を超える文字列では、常に [text] タグを使う。
The tags [text] and [/text] can be used to delimit long strings and suppress escape character translation. This is useful for delimiting long HTML passages in CGI files written in newLISP or for situations where character translation should be completely suppressed. Always use the [text] tags for strings longer than 2048 characters.

sym

シンボル、または、シンボルに評価される式。
A symbol or expression evaluating to a symbol.

'xyz, (first '(+ - /)), '*, '- , someSymbol,

このマニュアルにあるコンテキスト・シンボルの多くは、他のシンボルと区別するために、大文字で始まっている。
Most of the context symbols in this manual start with an uppercase letter to distinguish them from other symbols.

sym-context

シンボル、存在するコンテキスト、または、コンテキストが生成されるシンボルに評価される式。 コンテキストが存在していない場合、多くの関数は無条件にコンテキストを生成する(例えば、bayes-traincontexteval-stringloadsymxml-parse)。 これらの関数が存在するコンテキストで使われる時、コンテキストは指定される必要がある。 いくつかの関数は、クォートされたシンボルを取ることで継続する(例えば、context)。 context? のような関数にとって、この区別は重要である。
(訳注:context にクォートされたシンボルを渡した場合、そのコンテキストが存在していない時は、生成され、そのコンテキストに入ります。 context? にクォートされたシンボルを渡した場合、nil になります。)
A symbol, an existing context, or an expression evaluating to a symbol from which a context will be created. If a context does not already exist, many functions implicitly create them (e.g., bayes-train, context, eval-string, load, sym, and xml-parse). The context must be specified when these functions are used on an existing context. Even if a context already exists, some functions may continue to take quoted symbols (e.g., context). For other functions, such as context?, the distinction is critical.



§ )

3. Functions in groups(グループ毎の関数)

いくつかの関数は複数のグループに現れます。
Some functions appear in more than one group.

List processing, flow control, and integer arithmetic(リスト処理、フロー制御と整数演算)

+, -, *, /, % 整数演算
integer arithmetic
++ 整数を加算する
increment integer numbers
-- 整数を減算する
decrement integer numbers
<, >, = あらゆるデータの比較:未満、超過、等号
compares any data type: less, greater, equal
<=, >=, != あらゆるデータの比較:以下、以上、不等号
compares any data type: less-equal, greater-equal, not-equal
: コンテキスト・シンボルを作成し、オブジェクトに適用する
constructs a context symbol and applies it to an object
and 論理積
logical and
append リスト、アレイ、文字列を結合し、新しいリスト、アレイ、文字列を形成する
appends lists ,arrays or strings to form a new list, array or string
apply 関数や組込関数を引数のリストに適用する
applies a function or primitive to a list of arguments
args 関数やマクロ式の引数リストを取り出す
retrieves the argument list of a function or macro expression
assoc リストの連想キーワードを検索する
searches for keyword associations in a list
begin 関数のブロックを開始する
begins a block of functions
bigint 数値を大整数に変換する
convert a number to big integer format
bind リストの連想変数を束縛する
binds variable associations in a list
case 制御変数の内容で分岐する
branches depending on contents of control variable
catch 式の評価する、あるいは、エラーを補足する
evaluates an expression, possibly catching errors
chop リストの最後の要素をきり落とす
chops elements from the end of a list
clean リストから要素を取り除く
cleans elements from a list
collect 式を繰り返し評価し、結果をリストに集める
repeat evaluating an expression and collect results in a list
cond 式次第で分岐する
branches conditionally to expressions
cons リストの前に要素をつけ、新リストを作る
prepends an element to a list, making a new list
constant 定数シンボルを定義する
defines a constant symbol
count リストの要素が別のリストに出現する数を数える
counts elements of one list that occur in another list
curry 関数 fx(y) を関数 f(x, y) に変換する
transforms a function f(x, y) into a function fx(y)
define 新関数やラムダ式を定義する
defines a new function or lambda expression
define-macro マクロやラムダ・マクロ式を定義する
defines a macro or lambda-macro expression
def-new 異なるコンテキスト(名前空間)にシンボルをコピーする
copies a symbol to a different context (namespace)
difference 二つのリスト間の差を返す
returns the difference between two lists
doargs 関数の引数を通して繰り返す
iterates through the arguments of a function
dolist リストの各要素で一回ずつ評価する
evaluates once for each element in a list
dostring 文字列の各文字で一回ずつ評価する
evaluates once for each character in a string
dotimes 範囲内の各数字で一回ずつ評価する
evaluates once for each number in a range
dotree コンテキスト内のシンボルを通して一回ずつ評価する
iterates through the symbols of a context
do-until 条件が合致するまで式ブロックの評価を繰り返す
repeats evaluation of an expression until the condition is met
do-while 条件が真の間、式ブロックの評価を繰り返す
repeats evaluation of an expression while the condition is true
dup 指定された回数、リストか文字列を複製する
duplicates a list or string a specified number of times
ends-with 文字列かリストの終りと同じ型のキーとの一致をチェックする
checks the end of a string or list against a key of the same type
eval 式を評価する
evaluates an expression
exists リスト中の条件の存在をチェックする
checks for the existence of a condition in a list
expand 入れ子リスト中のシンボルを置き換える
replaces a symbol in a nested list
explode リストか文字列を分割する
explodes a list or string
extend リストか文字列を拡張する
extends a list or string
first リストか文字列の第一要素を取得する
gets the first element of a list or string
filter リストをフィルタする
filters a list
find リストか文字列中の要素を検索する
searches for an element in a list or string
flat (訳注:入れ子でない)フラットなリストを返す
returns the flattened list
fn 新関数やラムダ式を定義する
defines a new function or lambda expression
for 範囲内の各数字で一回ずつ評価する
evaluates once for each number in a range
for-all リスト中の全ての要素が条件と合うかどうかをチェックする
checks if all elements in a list meet a condition
if 条件によって式を評価する
evaluates an expression conditionally
if-not 条件によって式を評価する(訳注:if と論理が逆)
evaluates an expression conditionally
index リストから要素をフィルタし、それらのインデックスを返す
filters elements from a list and returns their indices
intersect 二つのリストの両方にある要素を返す
returns the intersection of two lists
lambda 新関数やラムダ式を定義する
defines a new function or lambda expression
last リストか文字列の最後の要素を(訳注:リストにしないで)返す
returns the last element of a list or string
length リストか文字列の長さを返す
calculates the length of a list or string
let ローカル変数を宣言し、初期化する
declares and initializes local variables
letex 式中にローカル変数を展開し、その後評価する
expands local variables into an expression, then evaluates
letn 入れ子の let のように、ローカル変数を初期化する
(訳注:先に定義されたシンボルの内容が展開される。Common Lisp の let* 相当)
initializes local variables incrementally, like nested lets
list リストを作る
makes a list
local ローカル変数を宣言する
declares local variables
lookup 連想リスト中のメンバーを調べる
looks up members in an association list
map リストの要素に関数を適用し、その結果を集める
maps a function over members of a list, collecting the results
match リストに対してパターン・マッチングする。文字列に対しては、findregex を参照
matches patterns against lists; for matching against strings, see find and regex
member リストか文字列のメンバーを見つける
finds a member of a list or string
not 論理否定
logical not
nth リストか文字列のn番目の要素を取得する
gets the nth element of a list or string
or 論理和
logical or
pop リストか文字列から要素を削除して返す
deletes and returns an element from a list or string
pop-assoc 連想リストから連想を取り去る
removes an association from an association list
push リストか文字列に新要素を挿入する
inserts a new element into a list or string
quote 式をクォートする
quotes an expression
ref 入れ子リスト中の要素の位置を返す
returns the position of an element inside a nested list
ref-all 入れ子リスト中の要素のインデックス・ベクターのリストを返す
returns a list of index vectors of elements inside a nested list
rest リストか文字列の第一要素以外を返す
returns all but the first element of a list or string
replace リストか文字列内の要素を置換する
replaces elements inside a list or string
reverse リストか文字列の並びを逆にする
reverses a list or string
rotate リストか文字列の並びを回転する
rotates a list or string
select リストか文字列から要素を選んで並べ換える
selects and permutes elements from a list or string
self FOOP メソッド内で目標オブジェクトをアクセスする
Accesses the target object inside a FOOP method
set 束縛やシンボルの内容を設定する
sets the binding or contents of a symbol
setf setq シンボル、リスト、アレイ、文字列参照の内容を設定する
sets contents of a symbol or list, array or string reference
set-ref 入れ子リスト中の要素を検索し、置き換える
searches for an element in a nested list and replaces it
set-ref-all 入れ子リスト中の要素を検索し、全ての検出を置き換える
searches for an element in a nested list and replaces all instances
silent begin のように動作するが、戻り値のコンソール出力を抑制する
works like begin but suppresses console output of the return value
slice リストか文字列の一部を取り出す
extracts a sublist or substring
sort リストのメンバーを並べ替える
sorts the members of a list
starts-with 文字列かリストの始まりと同じ型のキーとの一致をチェックする
checks the beginning of a string or list against a key of the same type
swap リストか文字列内の二つの要素を入れ替える
swaps two elements inside a list or string
unify 二つの式を統一化(ユニフィケーション)する
unifies two expressions
unique 重複しない要素のリストを返す
returns a list without duplicates
union 二つかそれ以上のリストで重複しない要素のリストを返す
returns a unique list of elements found in two or more lists.
unless 条件により(訳注:nil か '() の時)式ブロックを評価する
evaluates a block of statements conditionally
until 条件が合致するまで式ブロックの評価を繰り返す
repeats evaluation of an expression until the condition is met
when 条件により(訳注:nil か '() 以外の時)式ブロックを評価する
evaluates a block of statements conditionally
while 条件が真の間、式ブロックの評価を繰り返す
repeats evaluation of an expression while the condition is true

String and conversion functions(文字列と変換関数)

address 数値か文字列のメモリ・アドレスを取得する
gets the memory address of a number or string
bigint 数値を大整数に変換する
convert a number to big integer format
bits 数値をバイナリ表現に変換する
translates a number into binary representation
char 文字と ASCII コード間の変換をする
translates between characters and ASCII codes
chop 文字列の最後から文字を削除する
chops off characters from the end of a string
dostring 文字列の各文字列で一回ずつ評価する
evaluates once for each character in a string
dup 指定された回数、リストか文字列を複製する
duplicates a list or string a specified number of times
ends-with 文字列かリストの終りと同じ型のキーとの一致をチェックする
checks the end of a string or list against a key of the same type
encrypt ワン・タイム・パッド暗号化と文字列の解読をする
does a one-time?pad encryption and decryption of a string
eval-string 文字列をコンパイル(訳注:すなわち、newLISPソース解析)し、評価する
compiles, then evaluates a string
explode 文字列を文字のリストに変換する
transforms a string into a list of characters
extend リストか文字列を拡張する
extends a list or string
find リストか文字列中の要素を検索する
searches for an element in a list or string
find-all 文字列中でパターン・マッチングした全てをリストで返す
returns a list of all pattern matches found in string
first リストか文字列の第一要素を取得する
gets the first element in a list or string
float 文字列か整数を浮動小数点数に変換をする
translates a string or integer into a floating point number
format C 言語のように数値と文字列を整形する
formats numbers and strings as in the C language
get-char メモリ・アドレスから文字を取得する
gets a character from a memory address
get-float メモリ・アドレスから倍精度浮動小数点を取得する
gets a double float from a memory address
get-int   メモリ・アドレスから32ビット整数を取得する
gets a 32-bit integer from a memory address
get-long   メモリ・アドレスから64ビット整数を取得する
gets a long 64-bit integer from a memory address
get-string メモリ・アドレスから文字列を取得する
gets a string from a memory address
int 文字列か浮動小数点を整数に変換する
translates a string or float into an integer
join 文字列のリストを結合する
joins a list of strings
last リストか文字列の最後の要素を取得する
returns the last element of a list or string
lower-case 文字列を小文字に変換する
converts a string to lowercase characters
member リストか文字列のメンバーを検索する
finds a list or string member
name この関数は、削除されました。代わりに term を使ってください。
returns the name of a symbol or its context as a string
nth リストか文字列のn番目の要素を取得する
gets the nth element in a list or string
pack newLISP の式をバイナリ構造体にパックする
packs newLISP expressions into a binary structure
parse 文字列を トークン(訳注:ソースコードを構成する単語や記号の最小単位)に分解する
breaks a string into tokens
pop 文字列からポップする
pops from a string
push 文字列にプッシュする
pushes onto a string
regex Perlコンパチの正規表現検索を実行する
performs a Perl-compatible regular expression search
regex-comp 正規表現パターンを前以てコンパイルする
pre-compiles a regular expression pattern
replace リストか文字列内の要素を置換する
replaces elements in a list or string
rest リストか文字列の第一要素以外を取得する
gets all but the first element of a list or string
reverse リストか文字列の並びを逆にする
reverses a list or string
rotate リストか文字列の並びを回転する
rotates a list or string
select リストか文字列から要素を選んで並べ換える
selects and permutes elements from a list or string
setf setq 文字列参照の内容を設定する
sets contents of a string reference
slice 文字列かリストの一部を取り出す
extracts a substring or sublist
source シンボルに束縛を要求されているソースを文字列で返す
returns the source required to bind a symbol as a string
starts-with 文字列かリストの始まりと同じ型のキーとの一致をチェックする
checks the start of the string or list against a key string or list
string 何であれ文字列に変換する
transforms anything into a string
sym 文字列をシンボルに変換する
translates a string into a symbol
title-case 文字列の第一文字を大文字に変換する
converts the first character of a string to uppercase
trim 文字列の一端または両端でトリム(訳注:空白文字を削除)する
trims a string on one or both sides
unicode ASCII か UTF-8 を UCS-4 Unicode に変換する
converts ASCII or UTF-8 to UCS-4 Unicode
utf8 UCS-4 Unicode を UTF-8 に変換する
converts UCS-4 Unicode to UTF-8
utf8len UTF-8 文字列の長さを UTF-8 文字単位で返す
returns length of an UTF-8 string in UTF-8 characters
unpack バイナリ構造体を newLISP 式にアンパックする
unpacks a binary structure into newLISP expressions
upper-case 文字列を大文字に変換する
converts a string to uppercase characters

Floating point math and special functions(浮動小数点数学と特殊関数)

abs 数値の絶対値を返す
returns the absolute value of a number
acos 逆余弦関数
calculates the arc-cosine of a number
acosh 双曲線逆余弦関数
calculates the inverse hyperbolic cosine of a number
add 浮動小数点数か整数を加算し、浮動小数点数を返す
adds floating point or integer numbers and returns a floating point number
array アレイを作成する
creates an array
array-list アレイからリストに変換し返す
returns a list conversion from an array
asin 逆正弦関数
calculates the arcsine of a number
asinh 逆双曲線正弦関数
calculates the inverse hyperbolic sine of a number
atan 逆正接関数
calculates the arctangent of a number
atanh 逆双曲線正接関数
calculates the inverse hyperbolic tangent of a number
atan2 Y / X の逆正接を ラジアンで計算
computes the principal value of the arctangent of Y / X in radians
beta ベータ関数
calculates the beta function
betai 不完全ベータ関数
calculates the incomplete beta function
binomial 二項分布関数
calculates the binomial function
ceil 切り上げ
rounds up to the next integer
cos 余弦関数
calculates the cosine of a number
cosh 双曲線余弦関数
calculates the hyperbolic cosine of a number
crc32 データ・バッファの32ビットCRCを計算する
calculates a 32-bit CRC for a data buffer
dec 変数、リスト、アレイ中の数値を減算する
decrements a number in a variable, list or array
div 浮動小数点数か整数を除算する
divides floating point or integer numbers
erf 誤差関数
calculates the error function of a number
exp 指数関数
calculates the exponential e of a number
factor 数値を素因数分解する
factors a number into primes
fft 高速フーリエ変換
performs a fast Fourier transform (FFT)
floor 切り捨て
rounds down to the next integer
flt 浮動小数点数を表す32ビット整数に変換する
converts a number to a 32-bit integer representing a float
gammai 不完全ガンマ関数
calculates the incomplete Gamma function
gammaln 対数ガンマ関数
calculates the log Gamma function
gcd 最大公約数を計算する
calculates the greatest common divisor of a group of integers
ifft 逆高速フーリエ変換
performs an inverse fast Fourier transform (IFFT)
inc 変数、リスト、アレイ中の数値を加算する
increments a number in a variable, list or array
inf? 無限大をチェックする
checks if a floating point value is infinite
log 対数を計算する
calculates the natural or other logarithm of a number
min 最小値検出
finds the smallest value in a series of values
max 最大値検出
finds the largest value in a series of values
mod 余りを計算する
calculates the modulo of two numbers
mul 浮動小数点数か整数を乗算する
multiplies floating point or integer numbers
NaN? NaN をチェックする
checks if a float is NaN (not a number)
round 数値を丸める
rounds a number
pow xy 乗を計算する
calculates x to the power of y
sequence 等差数列リストを生成する
generates a list sequence of numbers
series 等比数列リストを生成する
creates a geometric sequence of numbers
sgn 符号を取り出す
calculates the signum function of a number
sin 正弦関数
calculates the sine of a number
sinh 双曲線正弦関数
calculates the hyperbolic sine of a number
sqrt 平方根を計算する
calculates the square root of a number
ssq ベクトルの二乗和を計算する
calculates the sum of squares of a vector
sub 浮動小数点数か整数を減算する
subtracts floating point or integer numbers
tan 正接関数
calculates the tangent of a number
tanh 双曲線正接関数
calculates the hyperbolic tangent of a number
uuid  汎用一意識別子(UUID)を返す
returns a UUID (Universal Unique IDentifier)

Matrix functions(行列関数)

det 行列式
returns the determinant of a matrix
invert 逆行列を返す
returns the inversion of a matrix
mat 行列のスカラー演算を実行する
performs scalar operations on matrices
multiply 行列の積をとる
multiplies two matrices
transpose  行列を置換する
returns the transposition of a matrix

Array functions(アレイ関数)

append アレイを結合する
appends arrays
array 16次元までのアレイを作成し、初期化する
creates and initializes an array with up to 16 dimensions
array-list アレイをリストに変換する
converts an array into a list
array? アレイかどうかをチェックする
checks if expression is an array
det 行列式を返す
returns the determinant of a matrix
first アレイの第1要素を返す
returns the first row of an array
invert 逆行列を返す
returns the inversion of a matrix
last アレイの最後の要素を返す
returns the last row of an array
mat 行列のスカラー演算を実行する
performs scalar operations on matrices
multiply 行列の積をとる
multiplies two matrices
nth アレイの要素を返す
returns an element of an array
rest アレイの第一要素以外を返す
returns all but the first row of an array
setf アレイの参照内容を設定する
sets contents of an array reference
slice アレイの一部を返す
returns a slice of an array
transpose 行列を置換する
transposes a matrix

Bit operators(ビット演算子)

<<, >>    左ビット・シフト、右ビット・シフト
bit shift left, bit shift right
& ビット単位の論理積
bitwise and
| ビット単位の論理和
bitwise inclusive or
^ ビット単位の排他的論理和
bitwise exclusive or
~ ビット単位の論理否定
bitwise not

Predicates(述語)

(訳注:述語の意味は、こちらをどうぞ。)

atom? アトムのチェック
checks if an expression is an atom
array? アレイのチェック
checks if an expression is an array
bigint? 大整数のチェック
checks if a number is a big integer
context? コンテキストのチェック
checks if an expression is a context
directory? ディレクトリのチェック
checks if a disk node is a directory
empty? 空リストか空文字列のチェック
checks if a list or string is empty
even? 整数の偶奇をチェック
checks the parity of an integer number
file? ファイルの存在チェック
checks if a file exists
float? 浮動小数点数のチェック
checks if an expression is a float
global? シンボルのグローバルのチェック
checks if a symbol is global
inf? 無限大のチェック
checks if a floating point value is infinite
integer? 整数のチェック
checks if an expression is an integer
lambda? ラムダ式のチェック
checks if an expression is a lambda expression
legal? シンボルの適正チェック
checks if a string contains a legal symbol
list? リストのチェック
checks if an expression is a list
macro? ラムダ・マクロ式のチェック
checks if an expression is a lambda-macro expression
NaN? NaN のチェック
checks if a float is NaN (not a number)
nil? nil のチェック
checks if an expression is nil
null? nil, "", (), 0, 0.0のチェック
checks if an expression is nil, "", (), 0 or 0.0
number? 数値のチェック
checks if an expression is a float or an integer
odd? 整数の奇数をチェック
checks the parity of an integer number
protected? プロテクトのチェック
checks if a symbol is protected
primitive? 組込のチェック
checks if an expression is a primitive
quote? クォートのチェック
checks if an expression is quoted
string? 文字列のチェック
checks if an expression is a string
symbol? シンボルのチェック
checks if an expression is a symbol
true? nil以外のチェック
checks if an expression is not nil
zero? ゼロのチェック
checks if an expression is 0 or 0.0

Date and time functions(日付と時刻の関数)

date date-time 値を文字列に変換する
converts a date-time value to a string
date-list (訳注:1970年1月1日からの)秒数から年月日時分秒のリストを返す
returns a list of year, month, day, hours, minutes, seconds from a time value in seconds
date-parse 日付文字を解析し、1970年1月1日からの秒数を返す(以前は、parse-date
parses a date string and returns the number of seconds passed since January 1, 1970, (formerly parse-date)
date-value 日付と時刻に対して、1970年1月1日からの秒数を返す
calculates the time in seconds since January 1, 1970 for a date and time
now 現在の日付・時刻の情報をリストで返す
returns a list of current date-time information
time 式の評価に要する時間をミリ秒単位で計測する
calculates the time it takes to evaluate an expression in milliseconds
time-of-day その日で経過した時間をミリ秒数で返す
calculates the number of milliseconds elapsed since the day started

Statistics, simulation and modeling functions(統計、シミュレーション、モデル化関数)

amb 引数からランダムに選択し、それを評価する
randomly selects an argument and evaluates it
bayes-query データ・セットのベイズ確率を計算する
calculates Bayesian probabilities for a data set
bayes-train ベイズ法か頻度解析のリストで要素を数える
counts items in lists for Bayesian or frequency analysis
corr 積率相関 係数を計算する
calculates the product-moment correlation coefficient
crit-chi2 与えられた確率のカイ二乗 統計値を計算する
calculates the Chi² statistic for a given probability
crit-f 与えられた確率の F 統計値を計算する
calculates the F statistic for a given probability
crit-t 与えられた確率の スチューデントのt 統計値を計算する
calculates the Student's t statistic for a given probability
crit-z 与えられた確率の正規分布 Z 統計値を計算する
calculates the normal distributed Z for a given probability
kmeans-query クラスタの重心やデータ・ポイントまでの距離を計算する
calculates distances to cluster centroids or other data points
kmeans-train 一連のデータをクラスターに区分けする
partitions a data set into clusters
normal 正規分布する浮動小数点数のリストを生成する
makes a list of normal distributed floating point numbers
prob-chi2 カイ二乗 分布の尾部片側の確率を計算する
calculates the tail probability of a Chi² distribution value
prob-f F 分布の尾部片側の確率を計算する
calculates the tail probability of a F distribution value
prob-t スチューデントのt 分布の尾部片側の確率を計算する
calculates the tail probability of a Student's t distribution value
prob-z Z 分散値の累積確率を計算する
calculates the cumulated probability of a Z distribution value
rand ある範囲の乱数を生成する
generates random numbers in a range
random 均等に分布する浮動小数点数のリストを生成する
generates a list of evenly distributed floats
randomize リスト中のすべての要素をシャッフルする
shuffles all of the elements in a list
seed 内部乱数発生器の種を指定する
seeds the internal random number generator
stats ベクトル・データの基本的統計値を計算する
calculates some basic statistics for a data vector
t-test スチューデントのt 統計値を使って、データ・サンプルの平均を比較する
compares means of data samples using the Student's t statistic

Pattern matching(パターン マッチング)

ends-with リストか文字列の終りとパターンの一致をチェックする
tests if a list or string ends with a pattern
find リストか文字列中のパターンを検索する
searches for a pattern in a list or string
find-all 文字列中のパターンの出現を全て検索する
finds all occurrences of a pattern in a string
match リストのパターン・マッチング
matches list patterns
parse パターンに従って文字列を分解する
breaks a string along around patterns
ref 入れ子リスト中の要素の位置を返す
returns the position of an element inside a nested list
ref-all 入れ子リスト中の要素のインデックス・ベクトルのリストを返す
returns a list of index vectors of elements inside a nested list
regex 文字列中のパターンを検出する
finds patterns in a string
replace 文字列中のパターンを置き換える
replaces patterns in a string
search ファイル中のパターンを検索する
searches for a pattern in a file
starts-with リストか文字列の最初とパターンの一致をチェックする
tests if a list or string starts with a pattern
unify パターンの論理的単一化ユニフィケーションを実行する
performs a logical unification of patterns

Financial math functions(財務関数)

fv 投資の将来価値を返す
returns the future value of an investment
irr 内部利益率を計算する
calculates the internal rate of return
nper 投資に必要な支払回数を計算する
calculates the number of periods for an investment
npv 投資の現在価値を計算する
calculates the net present value of an investment
pv 投資の正味現在価値を計算する
calculates the present value of an investment
pmt ローンの定期支払額を計算する
calculates the payment for a loan

Input/output and file operations(ファイルと I/O の操作)

append-file ファイルにデータを追加する
appends data to a file
close ファイルを閉じる
closes a file
current-line 最後の read-line バッファの内容を取り出す
retrieves contents of last read-line buffer
device 現在の出力デバイスの設定または問合せ
sets or inquires about current print device
exec 別のプログラムを起動し、それに読み書きする
launches another program, then reads from or writes to it
load newLISP コードのファイルをロードし、評価する
loads and evaluates a file of newLISP code
open 読み書き用にファイルを開く
opens a file for reading or writing
peek ファイル記述子デスクリプタに読み取りできるバイト数をチェックする
checks file descriptor for number of bytes ready for reading
print コンソールかデバイスに出力する
prints to the console or a device
println コンソールかデバイスに改行付きで出力する
prints to the console or a device with a line-feed
read ファイルからバイナリ・データを読み取る
reads binary data from a file
read-char ファイルから8ビット文字を一個読み取る
reads an 8-bit character from a file
read-file 一動作でファイルを全て読み取る
reads a whole file in one operation
read-key キーボードのキーを読み取る
reads a keyboard key
read-line コンソールかファイルから一行読み取る
reads a line from the console or file
read-utf8 ファイルからUTF-8文字を読み取る
reads an UTF-8 character from a file
save ワークスペース、コンテキスト、シンボルをファイルに書き込む
saves a workspace, context, or symbol to a file
search 文字列についてファイルを検索する
searches a file for a string
seek ファイル・ポジションを設定、または読み取る
sets or reads a file position
write ファイルや文字列にバイナリ・データを書き込む
writes binary data to a file or string
write-char ファイルに一文字書き込む
writes a character to a file
write-file 一動作でファイルを書き込む
writes a file in one operation
write-line コンソールかファイルに一行書き込む
writes a line to the console or a file

Processes and the Cilk API(プロセスと CilK API)

! オペレーティング・システムのシェルに出る
shells out to the operating system
abort spawn で開始した子プロセスを中断する
aborts a child process started with spawn
destroy forkprocess で生成したプロセスを破棄する
destroys a process created with fork or process
exec プロセスを走らせ、それに読み書きする
runs a process, then reads from or writes to it
fork newLISP 子プロセスを起動する
launches a newLISP child process
pipe プロセス間通信用パイプを生成する
creates a pipe for interprocess communication
process 子プロセスを起動し、標準I/O と 標準エラーを割り当てる
launches a child process, remapping standard I/O and standard error
receive 他のプロセスからのメッセージを受信する
receive a message from another process
semaphore セマフォの生成と制御
creates and controls semaphores
send 他のプロセスにメッセージを送信する
send a message to another process
share 他のプロセスとメモリを共有する
shares memory with other processes
spawn Cilk プロセス管理で子プロセスを起動する
launches a child process for Cilk process management
sync spawn で起動した子プロセスを待ち、結果を収集する
waits for child processes launched with spawn and collects results
wait-pid 子プロセスが終わるまで待つ
waits for a child process to end

File and directory management(ファイルとディレクトリの管理)

change-dir  違うドライブやディレクトリに変更する
changes to a different drive and directory
copy-file ファイルをコピーする
copies a file
delete-file ファイルを削除する
deletes a file
directory ディレクトリ・エントリのリストを返す
returns a list of directory entries
file-info ファイルのサイズ、時間、属性を取得する
gets file size, date, time, and attributes
make-dir 新ディレクトリを作成する
makes a new directory
real-path 相対ファイル・パスの絶対ファイル・パスを返す
returns the full path of the relative file path
remove-dir 空のディレクトリを削除する
removes an empty directory
rename-file ファイルまたはディレクトリの名前を変える
renames a file or directory

HTTP networking API(HTTP ネットワーキング API)

base64-enc 文字列を BASE64 形式にエンコードする
encodes a string into BASE64 format
base64-dec BASE64 形式から文字列にデコードする
decodes a string from BASE64 format
delete-url ウェブからファイルまたはページを削除する
deletes a file or page from the web
get-url ウェブからファイルまたはページを読み取る
reads a file or page from the web
json-error JSON 変換で失敗したエラー情報を
returns error information from a failed JSON translation.
json-parse JSON 形式データを解析する
parses JSON formatted data
post-url URL アドレスにポストする
posts info to a URL address
put-url URL アドレスにページをアップロードする
uploads a page to a URL address
xfer-event HTTP バイト転送用のイベント・ハンドラを登録する
registers an event handler for HTTP byte transfers
xml-error 最後の XML 解析エラーを返す
returns last XML parse error
xml-parse XML ドキュメント を解析する
parses an XML document
xml-type-tags  XML タイプのタグを示すまたは変更する
shows or modifies XML type tags

Socket TCP/IP, UDP and ICMP network API(ソケット TCP/IP、UDP と ICMP ネットワーク API)

net-accept 受信用接続を受け付る
accepts a new incoming connection
net-close ソケット接続を閉じる
closes a socket connection
net-connect リモート・ホストに接続する
connects to a remote host
net-error 最後のエラーを返す
returns the last error
net-eval 複数のリモート newLISP サーバーで式を評価する
evaluates expressions on multiple remote newLISP servers
net-interface マルチホーム・コンピュータの既定インターフェース IP アドレスをセットする
Sets the default interface IP address on multihomed computers.
net-ipv インターネット・プロトコル・バージョン IPv4 と IPv6 間を切り替える
Switches between IPv4 and IPv6 internet protocol versions.
net-listen 通信用ローカル・ソケットを待ち受け(listen)る
listens for connections to a local socket
net-local 通信用ローカル IP とポート番号を返す
returns the local IP and port number for a connection
net-lookup IP 番号用の名前を返す
returns the name for an IP number
net-packet 生のソケット上にカスタム構成の IP パケットを送信する
send a custom configured IP packet over raw sockets
net-peek ネットワーク・ソケットから読み出せる文字数を返す
returns the number of characters ready to be read from a network socket
net-peer ネット接続用リモート IP とポートを返す
returns the remote IP and port for a net connect
net-ping 一個以上のアドレスに ping パケット (ICMP echo request) を送信する
sends a ping packet (ICMP echo request) to one or more addresses
net-receive 接続ソケット上のデータを読み取る
reads data on a socket connection
net-receive-from  開いてる接続の UDP を読み取る
reads a UDP on an open connection
net-receive-udp UDP を読み取り、接続を閉じる
reads a UDP and closes the connection
net-select ソケットまたはソケットのリストの状態をチェックする
checks a socket or list of sockets for status
net-send 接続ソケットにデータを送信する
sends data on a socket connection
net-send-to 開いてる接続に UDP を送信する
sends a UDP on an open connection
net-send-udp UDP を送信し、接続を閉じる
sends a UDP and closes the connection
net-service サービス名をポート番号に翻訳する
translates a service name into a port number
net-sessions 現在開いてる接続のリストを返す
returns a list of currently open connections

API for newLISP in a web browser(ウェブ・ブラウザ用 newLISP の API)

display-html ウェブ・ブラウザに HTML ページを表示する
display an HTML page in a web browser
eval-string-js 現在のウェブ・ブラウザ・ページで JavaScript を評価する
evaluate JavaScript in the current web browser page

Reflection and customization(リフレクションとカスタマイズ)

(訳注:Reflection については、こちらを参照してください。)

command-event コマンドラインや HTTP リスクエストを前処理する
pre-processes the command-line and HTTP requests
error-event エラー・ハンドラを定義する
defines an error handler
history 関数の呼び出し履歴を返す
returns the call history of a function
last-error エラー番号とテキストを報告する
report the last error number and text
macro リーダー拡張マクロ(訳注:macro)を生成する
create a reader expansion macro
ostype OSプラットフォームを表す文字列を取得する
contains a string describing the OS platform
prefix シンボルのコンテキストを返す
Returns the context prefix of a symbol
prompt-event インタラクティブ newLISP シェル・プロンプトをカスタマイズする
customizes the interactive newLISP shell prompt
read-expr ソースから S 式を読み取り、翻訳する
reads and translates s-expressions from source
reader-event 評価イベント駆動の前に、式を前処理する
preprocess expressions before evaluation event-driven
set-locale 異なるロケールに切り替える
switches to a different locale
source シンボルに束縛を要求されているソースを文字列で返す
returns the source required to bind a symbol to a string
sys-error OS システム・エラー番号を報告する
reports OS system error numbers
sys-info システム・リソースについての情報を与える
gives information about system resources
term コンテキスト無しのシンボル部分を文字列で返す
returns the term part of a symbol without the context prefix as a string

System functions(システム関数)

$ システム変数 $0 -> $15 にアクセスする
accesses system variables $0 -> $15
callback 導入した関数用のコールバック関数を登録する
registers a callback function for an imported library
catch 式を評価し、エラーを補足したら、すぐに戻る
evaluates an expression, catching errors and early returns
context 異なる名前空間の生成か切り替えをする
creates or switches to a different namespace
copy 評価結果をコピーする
copies the result of an evaluation
debug ユーザ定義関数をデバックする
debugs a user-defined function
delete シンボル・テーブルからシンボルを削除する
deletes symbols from the symbol table
default コンテキストのデフォルト・ファンクタを返す
returns the contents of a default functor from a context
env オペレーティング・システム環境を取得または設定する
gets or sets the operating system's environment
exit newLISPを終了し、戻り値をセットする
exits newLISP, setting the exit value
global MAIN以外から(訳注:MAINコンテキストを指定せずに)アクセスできるシンボルにする
makes a symbol accessible outside MAIN
import 共有ライブラリを導入する
imports a function from a shared library
main-args コマンドライン引数を取得する
gets command-line arguments
new コンテキストのコピーを生成する
creates a copy of a context
pretty-print pretty-print 文字(訳注: printsavesource 時の整形文字)を変更する
changes the pretty-printing characteristics
read-expr 文字列を S 式に翻訳するが、評価はしない
translates a string to an s-expression without evaluating it
reset トップレベルに行く(訳注:いわゆる、リセット)
goes to the top level
signal シグナル・ハンドラを設定する
sets a signal handler
sleep 指定されたミリ秒プロセスを中断する
suspends processing for specified milliseconds
sym 文字列からシンボルを生成する
creates a symbol from a string
symbols システムの全てのシンボルのリストを返す
returns a list of all symbols in the system
throw 先行する catch への戻りを起こす
causes a previous catch to return
throw-error ユーザ定義エラーを発生する
throws a user-defined error
timer ワン・ショット・タイマを開始して、イベントを起こす
starts a one-shot timer, firing an event
trace トレース・モードの設定と問い合わせ
sets or inquires about trace mode
trace-highlight トレース・モード時のハイライト文字列の設定
sets highlighting strings in trace mode

Importing libraries(ライブラリのインポート)

address 数値や文字列のメモリ・アドレスを返す
returns the memory address of a number or string
callback 導入した関数用のコールバック関数を登録する
registers a callback function for an imported library
flt 浮動小数点数を表す32ビット整数に変換する
converts a number to a 32-bit integer representing a float
float 文字列や整数を浮動小数点数に変換する
translates a string or integer into a floating point number
get-char メモリ・アドレスから文字を取得する
gets a character from a memory address
get-float メモリ・アドレスから倍精度浮動小数点を取得する
gets a double float from a memory address
get-int   メモリ・アドレスから32ビット整数を取得する
gets a 32-bit integer from a memory address
get-long   メモリ・アドレスから64ビット整数を取得する
gets a long 64-bit integer from a memory address
get-string メモリ・アドレスから文字列を取得する
gets a string from a memory address
import 共有ライブラリから関数を導入する
imports a function from a shared library
int 文字列か浮動小数点数を整数に変換する
translates a string or float into an integer
pack newLISP の式をバイナリ構造体にパックする
packs newLISP expressions into a binary structure
struct C言語タイプの構造体データを定義する
Defines a data structure with C types
unpack バイナリ構造体を newLISP 式にアンパックする
unpacks a binary structure into newLISP expressions

newLISP internals API(newLISP 内部 API)

command-event コマンドラインや HTTP リスクエストを前処理する
pre-processes the command-line and HTTP requests
cpymem アドレス間でメモリをコピーする
copies memory between addresses
dump newLISP セルのメモリ・アドレスと内容を示す
shows memory address and contents of newLISP cells
prompt-event インタラクティブ newLISP シェル・プロンプトをカスタマイズする
customizes the interactive newLISP shell prompt
read-expr ソースから S 式を読み取り、翻訳する
reads and translates s-expressions from source
reader-event 評価イベント駆動の前に、式を前処理する
preprocess expressions before evaluation event-driven


§ )

4. Functions in alphabetical order(アルファベット順の関数)


!

syntax: (! str-shell-command [int-flags])

OSのシェル上で str-shell-command のコマンドを実行します。 この関数は、ホスト・オペレーティング・システムによって異なる値を返します。
Executes the command in str-command by shelling out to the operating system and executing. This function returns a different value depending on the host operating system.

(! "vi")  
(! "ls -ltr")

シェル・コマンドを実行したり、標準出力を取得したり、標準入力を与えたりするのに関数exec を使ってください。 ノン・ブロッキングの子プロセスを起動し、標準 I/O や標準エラーをパイプへリダイレクトするためには、関数process が使えます。
Use the exec function to execute a shell command and capture the standard output or to feed standard input. The process function may be used to launch a non-blocking child process and redirect std I/O and std error to pipes.

Ms Windows では、オプションの int-flags パラメータが、 プロセス生成の様々なパラメータを制御する Windows 関数 CreateProcessA 用に定義されたプロセス生成フラグを取ります。 このパラメータ―― 0 が使われる――を含めると、コマンド・シェル・ウィンドウ無しプロセス生成が強制されます。 このパラメータは、Unix では無視されます。
On Ms Windows the optional int-flags parameter takes process creation flags as defined for the Windows CreateProcessA function to control various parameters of process creation. The inclusion of this parameter – which also can be 0 – forces a different creation of the process without a command shell window. This parameter is ignored on Unix.

; on MS Windows
; close the console of the currently running newLISP process
(apply (import "kernel32" "FreeConsole")) 

; start another process and wait for it to finish
(! "notepad.exe" 0)

(exit)

付加パラメータ無しの ! 呼出しは、コマンド・ウィンドウを閉じて、代わりに新しいコマンド・ウィンドウを生成します。
Without the additional parameter, the ! call would create a new command window replacing the closed one.

!(感嘆符)は、括弧や ! に続くスペースを省略して、 コマンド・ラインのシェル・オペレータとしても使えることに注意してください:
Note that ! (exclamation mark) can be also be used as a command-line shell operator by omitting the parenthesis and space after the !:

> !ls -ltr    ; executed in the newLISP shell window

この方法で使う ! オペレータは全く newLISP 関数らしくなく、いわば newLISP コマンド・シェルの特殊機能です。 ! は、必ずコマンド・ラインの先頭に、入力しなければなりません。
Used in this way, the ! operator is not a newLISP function at all, but rather a special feature of the newLISP command shell. The ! must be entered as the first character on the command-line.



$

syntax: ($ int-idx)

正規表現を使う関数(directoryends-withfindfind-allparseregexsearchstarts-withreplace)は全て、 実行中もしくは実行後の関数の結果をシステム変数として予約されている $0$1$2$15 に束縛します。 システム変数は他のシンボルと同じように扱えます。 選択肢の一つとして、これらの変数の内容を ($ 0)($ 1)($ 2) 等を使ってアクセスすることもできます。 この方法はインデックス操作を使っています(すなわち ($ i)、ここで i は整数)。
The functions that use regular expressions (directory, ends-with, find, find-all, parse, regex, search, starts-with and replace) all bind their results to the predefined system variables $0, $1, $2$15 after or during the function's execution. System variables can be treated the same as any other symbol. As an alternative, the contents of these variables may also be accessed by using ($ 0), ($ 1), ($ 2), etc. This method allows indexed access (i.e., ($ i), where i is an integer).

(set 'str  "http://newlisp.org:80")
(find "http://(.*):(.*)" str 0)   0
                                 
$0   "http://newlisp.org:80"
$1   "newlisp.org"
$2   "80"
                                 
($ 0)   "http://newlisp.org:80"
($ 1)   "newlisp.org"
($ 2)   "80"


+, -, *, / ,%  bigint

syntax: (+ int-1 [int-2 ... ])

int-1 から続く全ての数値の和を返します。
Returns the sum of all numbers in int-1 —.

syntax: (- int-1 [int-2 ... ])

int-1 から int-2 を引き算し、続く int-i 以下を前の結果から次々に引き算します。もし、引数が一つなら、符号を反転します。
Subtracts int-2 from int-1, then the next int-i from the previous result. If only one argument is given, its sign is reversed.

syntax: (* int-1 [int-2 ... ])

int-1 から int-i までを掛け算します。
The product is calculated for int-1 to int-i.

syntax: (/ int-1 [int-2 ... ])

リストの終わりに達するまで、次々と割り算して行きます。 ゼロで割るとエラーを起こします。
Each result is divided successively until the end of the list is reached. Division by zero causes an error.

syntax: (% int-1 [int-2 ... ])

次(訳注:右隣)の int で割った余りを返します。 ゼロでの割り算はエラーを起こします。 浮動小数点数の場合は、関数 modを使ってください。
Each result is divided successively by the next int, then the rest (modulo operation) is returned. Division by zero causes an error. For floating point numbers, use the mod function.

(+ 1 2 3 4 5)         15
(+ 1 2 (- 5 2) 8)     14
(- 10 3 2 1)          4
(- (* 3 4) 6 1 2)     3
(- 123)               -123
(map - '(10 20 30))   (-10 -20 -30)
(* 1 2 3)             6
(* 10 (- 8 2))        60
(/ 12 3)              4
(/ 120 3 20 2)        1
(% 10 3)              1
(% -10 3)             -1
(+ 1.2 3.9)           4

+-*/% の引数に与えられた浮動小数点数は、0(ゼロ)に近い整数に丸められます。
Floating point values in arguments to +, -, *, /, and % are truncated to the integer value closest to 0 (zero).

整数値の最大値(9,223,372,036,854,775,807)より大きい浮動小数点数は整数値の最大値に丸められ、 最小値(-9,223,372,036,854,775,808) より小さい浮動小数点数は整数値の最小値に丸められます。 これは、+Inf-Inf も含みます。
Floating point values larger or smaller than the maximum (9,223,372,036,854,775,807) or minimum (-9,223,372,036,854,775,808) integer values are truncated to those values. This includes the values for +Inf and -Inf.

計算結果が 9,223,372,036,854,775,807 より大きい値になると符合が+から-に、 -9,223,372,036,854,775,808 より小さい値になると符合が-から+に変わります。
Calculations resulting in values larger than 9,223,372,036,854,775,807 or smaller than -9,223,372,036,854,775,808 wrap around from positive to negative or negative to positive.

(訳例:
> (+ 9223372036854775807 1)
-9223372036854775808
> (- -9223372036854775808 1)
9223372036854775807
> 

NaN (Not a Number) に評価される浮動小数点数は 0(ゼロ)として扱われます。
Floating point values that evaluate to NaN (Not a Number), ar treated as 0 (zero).

(訳例:
> (sqrt -1)
nan
> (+ 0 (sqrt -1))
0
> (mul 1E308 10)
inf
> (+ 0 (mul 1E308 10))
9223372036854775807
> (mul 1E308 -10)
-inf
> (+ 0 (mul 1E308 -10))
9223372036854775807
> 


++ !  bigint

syntax: (++ place [num ... ])

++ 演算子は incのように動作しますが、実行されるのは整数演算です。 オプションの引数 num が無い時、++place の数値に 1 を加算します。
The ++ operator works like inc, but performs integer arithmetic. Without the optional argument in num, ++ increments the number in place by 1.

引数に浮動小数点数が渡されると、最初に小数点以下が切り捨てられます。
If floating point numbers are passed as arguments, their fractional part gets truncated first.

計算結果が 9,223,372,036,854,775,807 より大きい値になると符合が正から負に、-9,223,372,036,854,775,808 より小さい値になると符合が負から正に変わります。
Calculations resulting in numbers greater than 9,223,372,036,854,775,807 wrap around to negative numbers. Results smaller than -9,223,372,036,854,775,808 wrap around to positive numbers.

place はシンボルか、数値を保持するリスト構造の位置か、式によって返される数値のいずれかです。
place is either a symbol or a place in a list structure holding a number, or a number returned by an expression.

(set 'x 1)    
(++ x)         2
(set 'x 3.8)
(++ x)         4
(++ x 1.3)     5
(set 'lst '(1 2 3))
(++ (lst 1) 2))   4
lst               (1 4 3)

place のシンボルに nil が入っていたら、0 として扱われます。
If the symbol for place contains nil, it is treated as if containing 0.

整数モードで数値を減算するには -- を見てください。 浮動小数点数モードで数値を加算するには inc を見てください。
See -- for decrementing numbers in integer mode. See inc for incrementing numbers in floating point mode.



-- !  bigint

syntax: (-- place [num ... ])

-- 演算子は dec のように動作しますが、実行されるのは整数演算です。 オプションの引数 num が無い時、--place の数値から 1 を引きます。
The -- operator works like dec, but performs integer arithmetic. Without the optional argument in num-2, -- decrements the number in place by 1.

引数に浮動小数点数が渡されると、最初に小数点以下が切り捨てられます。
If floating point numbers are passed as arguments, their fractional part gets truncated first.

計算結果が 9,223,372,036,854,775,807 より大きい値になると符合が正から負に、 -9,223,372,036,854,775,808 より小さい値になると符合が負から正に変わります。
Calculations resulting in numbers greater than 9,223,372,036,854,775,807 wrap around to negative numbers. Results smaller than -9,223,372,036,854,775,808 wrap around to positive numbers.

place はシンボルか、数値を保持するリスト構造の位置か、式によって返される数値のいずれかです。
place is either a symbol or a place in a list structure holding a number, or a number returned by an expression.

(set 'x 1)    
(-- x)         0
(set 'x 3.8)
(-- x)         2
(-- x 1.3)     1


(set 'lst '(1 2 3))
(-- (lst 1) 2))   0
lst               (1 0 3)

place のシンボルに nil が入っていたら、0 として扱われます。
If the symbol for place contains nil, it is treated as if containing 0.

整数モードで数値を加算するには ++ を見てください。 浮動小数点数モードで数値を減算するには dec を見てください。
See ++ for incrementing numbers in integer mode. See dec for decrementing numbers in floating point mode.



<, >, =, <=, >=, !=  bigint

syntax: (< exp-1 [exp-2 ... ])
syntax: (> exp-1 [exp-2 ... ])
syntax: (= exp-1 [exp-2 ... ])
syntax: (<= exp-1 [exp-2 ... ])
syntax: (>= exp-1 [exp-2 ... ])
syntax: (!= exp-1 [exp-2 ... ])

式が評価され、その結果が続けて比較されます。 比較した結果が比較演算子に一致する間は、全ての引数が試されるまで評価と比較が続けられ、結果は、true になります。 比較が一致しなかったら、直ちに nil が返ります。
Expressions are evaluated and the results are compared successively. As long as the comparisons conform to the comparison operators, evaluation and comparison will continue until all arguments are tested and the result is true. As soon as one comparison fails, nil is returned.

全ての演算子で、引数が一つなら、第二引数は 0 として扱われます。 これは、数値が負か正か、ゼロかゼロでないか等を確認するのに使えます。
If only one argument is supplied, all comparison operators assume 0 (zero) as a second argument. This can be used to check if a number is negative, positive, zero or not zero.

全ての型の式(アトム、数値、シンボル、文字列)が比較可能です。 リスト式も比較可能です(リストの要素が再帰的に比較されます)。
All types of expressions can be compared: atoms, numbers, symbols, and strings. List expressions can also be compared (list elements are compared recursively).

リスト式の比較では、リストの最初の要素が続く要素よりも先に判断されます(文字列の文字も同様)。 長さも要素も異なるリスト式の比較では、長いリスト式がより大きいと判断されます(例題を見てください)。
When comparing lists, elements at the beginning of the list are considered more significant than the elements following (similar to characters in a string). When comparing lists of different lengths but equal elements, the longer list is considered greater (see examples).

混在型の式では、型が低い方から高い方に比較されます。 浮動小数点数と整数は、それらを数値として比較するため、最初に必要な型へ変換してから比較されます。
In mixed-type expressions, the types are compared from lowest to highest. Floats and integers are compared by first converting them to the needed type, then comparing them as numbers.

Atoms: nil, true, integer or float, string, symbol, primitive
Lists: quoted list/expression, list/expression, lambda, lambda-macro
(訳注:型の比較順列。左から右へ行くにつれて高くなり、
アトムとリストでは、リストの方が大きいと判断されます。)
(< 3 5 8 9)                      true
(> 4 2 3 6)                      nil
(< "a" "c" "d")                  true
(>= duba aba)                    true
(< '(3 4) '(1 5))                nil
(> '(1 2 3) '(1 2))              true
(= '(5 7 8) '(5 7 8))            true
(!= 1 4 3 7 3)                   true
(< 1.2 6 "Hello" 'any '(1 2 3))            true
(< nil true)                               true
(< '(((a b))) '(((b c))))                  true
(< '((a (b c)) '(a (b d)) '(a (b (d)))))   true

; with single argument compares against 0

(> 1)     true ; checks for positive
(> -1)    nil ; checks for negative
(= 123)   nil ; checks for zero

(map > '(1 3 -4 -3 1 2))    (true true nil nil true true)


<<, >>

syntax: (<< int-1 int-2 [int-3 ... ])
syntax: (>> int-1 int-2 [int-3 ... ])
syntax: (<< int-1)
syntax: (>> int-1)

数値 int-1int-2 で与えられたビット数分、左または右に算術シフトされ、続けて int-3 分シフトされるという風に続きます。 例えば、64ビット整数では 63 個までシフトできます。 右シフトの場合、最上位ビットがそのまま残ります(算術シフト):
The number int-1 is arithmetically shifted to the left or right by the number of bits given as int-2, then shifted by int-3 and so on. For example, 64-bit integers may be shifted up to 63 positions. When shifting right, the most significant bit is duplicated (arithmetic shift):

(>> 0x8000000000000000 1)   0xC000000000000000  ; not 0x0400000000000000!

(<< 1 3)        8
(<< 1 2 1)      8
(>> 1024 10)    1
(>> 160 2 2)   10

(<< 3)          6
(>> 8)          4

int-1 が唯一の引数の場合、<<>> は 1ビットシフトします。
When int-1 is the only argument, << and >> shift by one bit.



&

syntax: (& int-1 int-2 [int-3 ... ])

int-1 の数値と int-2 の数値のビット単位 and 演算を行います。 続く int-3 以下の数値に対しても同様です。
A bitwise and operation is performed on the number in int-1 with the number in int-2, then successively with int-3, etc.

(& 0xAABB 0x000F)   11  ; which is 0xB


|

syntax: (| int-1 int-2 [int-3 ... ])

int-1 の数値と int-2 の数値のビット単位 or 演算を行います。 続く int-3 以下の数値に対しても同様です。
A bitwise or operation is performed on the number in int-1 with the number in int-2, then successively with int-3, etc.

(| 0x10 0x80 2 1)   147


^

syntax: (^ int-1 int-2 [int-3 ... ])

int-1 の数値と int-2 の数値のビット単位 xor 演算を行います。 続く int-3 以下の数値に対しても同様です。
A bitwise xor operation is performed on the number in int-1 with the number in int-2, then successively with int-3, etc.

(^ 0xAA 0x55)   255


~

syntax: (~ int)

int の数値に対して、全てのビットを反転するビット単位 not 演算を行います。
A bitwise not operation is performed on the number in int, reversing all of the bits.

(format "%X" (~ 0xFFFFFFAA))   "55"
(~ 0xFFFFFFFF)                 0


:

syntax: (: sym-function list-object [ ... ])

コロンは名前空間のコンテキストとシンボル名を別けるために使われるだけでなく、演算子としても使われます。 演算子として使う時、コロン : はオブジェクト・リストのコンテキスト名のコンテキスト・シンボルとコロンに続くシンボルを組み立てます。 list-object のオブジェクト・リストは他のパラメータを続けることができます。
The colon is used not only as a syntactic separator between namespace prefix and the term inside but also as an operator. When used as an operator, the colon : constructs a context symbol from the context name in the object list and the symbol following the colon. The object list in list-object can be followed by other parameters.

演算子: は、コンテキスト(名前空間)によって表される異なるオブジェクト・クラスの部品となるオブジェクト・メソッド多態性を実装します。 newLISP では、オブジェクトは、第一要素がクラス・コンテキストのシンボル(名前)であるリストで表現されます。 クラス・コンテキストはオブジェクトに適用する関数群を実装します。コロンとそれに続くシンボルの間はスペース無しです。
The : operator implements polymorphism of object methods, which are part of different object classes represented by contexts (namespaces). In newLISP, an object is represented by a list, the first element of which is the symbol (name) of its class context. The class context implements the functions applicable to the object. No space is required between the colon and the symbol following it.

(define (Rectangle:area)
    (mul (self 3) (self 4)))

(define (Circle:area)
    (mul (pow (self 3) 2) (acos 0) 2))

(define (Rectangle:move dx dy)
    (inc (self 1) dx) 
	(inc (self 2) dy)) 

(define (Circle:move p dx dy)
    (inc (self 1) dx) (inc (self 2) dy)) 

(set 'myrect '(Rectangle 5 5 10 20)) ; x y width height
(set 'mycircle '(Circle 1 2 10)) ; x y radius

;; using the : (colon) operator to resolve to a specific context

(:area myrect)      200
(:area mycircle)    314.1592654

;; map class methods uses curry to enclose the colon operator and class function

(map (curry :area) (list myrect mycircle))  (200 314.1592654)

(map (curry :area) '((Rectangle 5 5 10 20) (Circle 1 2 10)))  (200 314.1592654) 

;; change object attributes using a function and re-assigning
;; to the objects name

(:move myrect 2 3)       
myrect    (Rectangle 7 8 10 20)

(:move mycircle 4 5)   
mycircle  (Circle 5 7 10)

FOOP メソッド内部では、メソッドの目的オブジェクトをアクセスするために関数 self が使えます。
Inside the FOOP methods the self function is used to access the target object of the method.



abort

syntax: (abort int-pid)
syntax: (abort)

第一形式の abort は、現在の親プロセスが与えるプロセスIDの int-pid で特定される子プロセスを中断します。 プロセスは spawn を使って開始されている必要があります。 fork を使って開始されたプロセスには、代わりに destroy を使います。
In the first form, abort aborts a specific child process of the current parent process giving the process id in int-pid. The process must have been started using spawn. For processes started using fork, use destroy instead.

MS Windows では、この関数 abort を利用できません。
The function abort is not available on Windows.

(abort 2245)   true

現プロセスから起動した全ての子プロセスを中断したい時は、引数無しの abort を使います:
To abort all child processes spawned from the current process use abort without any parameters:

(abort)   true ; abort all

関数 abort は、子プロセス同期とプロセス並列化用の Cilk API の部品です。 Cilk API の全貌については、関数spawn の項を見てください。
The function abort is part of the Cilk API for synchronizing child processes and process parallelization. See the reference for the function spawn for a full discussion of the Cilk API.



abs  bigint

syntax: (abs num)

数値 num の絶対値を返します。
Returns the absolute value of the number in num.

(abs -3.5)   3.5


acos

syntax: (acos num-radians)

数値 num-radians の逆余弦関数を計算します。
The arc-cosine function is calculated from the number in num-radians.

(acos 1)   0
(cos (acos 1))  1


acosh

syntax: (acosh num-radians)

num-radians の逆双曲線余弦関数を計算します。 ここで、num-radians は双曲線余弦関数値です。 num-radians が 1 より小さい時、acoshNaN を返します。
Calculates the inverse hyperbolic cosine of num-radians, the value whose hyperbolic cosine is num-radians. If num-radians is less than 1, acosh returns NaN.

(acosh 2)   1.316957897
(cosh (acosh 2))  2
(acosh 0.5)  NaN


add

syntax: (add num-1 [num-2 ... ])

num-1, num-2 と続く全ての数値を加算します。 add は浮動小数点数か整数の引数を取りますが、返すのは常に浮動小数点数です。 NaN となる浮動小数点数には NaN を返します。
All of the numbers in num-1, num-2, and on are summed. add accepts float or integer operands, but it always returns a floating point number. Any floating point calculation with NaN also returns NaN.

(add 2 3.25 9)    14.25
(add 1 2 3 4 5)   15


address

syntax: (address int)
syntax: (address float)
syntax: (address str)

整数 int、倍精度浮動小数点数 float、文字列 str のメモリ・アドレスを返します。 この関数は関数 import を使って導入されるライブラリ関数への変数引渡しに使われます。
Returns the memory address of the integer in int, the double floating point number in float, or the string in str. This function is used for passing parameters to library functions that have been imported using the import function.

(set 's "\001\002\003\004")

(get-char (+ (address s) 3))    4

(set 'x 12345) ; x is a 64-bit long int

; on a big-endian CPU, i.e. PPC or SPARC 
(get-long (address x))          12345
; the 32-bit int is in high 32-bit part of the long int
(get-int (+ (address x) 4))     12345

; on a little-endian CPU, i.e. Intel i386
; the 32-bit int is in the low 32-bit part of the long int
(get-int (address x))           12345

; on both architectures (integers are 64 bit in newLISP)
(set 'x 1234567890)
(get-long (address x))           1234567890

Cライブラリ関数に文字列を渡す時は、文字列のアドレスが自動的に使われますので address を使う必要はありません。 例が示すように、address は文字列アドレスのポインタ計算に使うことができます。
When a string is passed to C library function the address of the string is used automatically, and it is not necessary to use the address function in that case. As the example shows, address can be used to do pointer arithmetic on the string's address.

address は消えてなくなる中間式オブジェクトに対してではなく、変数シンボルで参照されるデータ・オブジェクトの実アドレスでのみ、使われるべきです。
address should only be used on persistent addresses from data objects referred to by a variable symbol, not from volatile intermediate expression objects.

関数 get-charget-intget-longget-float も見てください。
See also the get-char, get-int, get-long and get-float functions.



amb

syntax: (amb exp-1 [exp-2 ... ])

exp-1 ... n 中の一つが無作為に選択され、その評価結果が返ります。
One of the expressions exp-1 ... n is selected at random, and the evaluation result is returned.

(amb 'a 'b 'c 'd 'e)   one of: a, b, c, d, or e at random

(dotimes (x 10) (print (amb 3 5 7)))   35777535755

無作為な数値の選択に、newLISP は内部で rand と同じ関数を使います。 無作為な浮動小数点数の生成には、randomrandomizenormal を使ってください。 擬似乱数生成処理を特定の開始位置で初期化するには、seed を使ってください。
Internally, newLISP uses the same function as rand to pick a random number. To generate random floating point numbers, use random, randomize, or normal. To initialize the pseudo random number generating process at a specific starting point, use the seed function.



and

syntax: (and exp-1 [exp-2 ... ])

exp-1, exp-2, が順に評価され、最後の式の結果を返します。 もし、式が nil か空リスト () になれば、評価を終了し、nil か空リスト () を返します。
The expressions exp-1, exp-2, etc. are evaluated in order, returning the result of the last expression. If any of the expressions yield nil or the empty list (), evaluation is terminated and nil or the empty list () is returned.

(set 'x 10)                        10
(and (< x 100) (> x 2))            true
(and (< x 100) (> x 2) "passed")   "passed"
(and '())                          ()
(and true)                         true
(and)                              true


append

syntax: (append list-1 [list-2 ... ])
syntax: (append array-1 [array-2 ... ])
syntax: (append str-1 [str-2 ... ])

第一形式の append はリストに作用し、list-1 から list-n までを一つの新しいリストに結合します。 元のリスト群は変わりません。(訳注:つまり、副作用がない)
In the first form, append works with lists, appending list-1 through list-n to form a new list. The original lists are left unchanged.

(append '(1 2 3) '(4 5 6) '(a b))   (1 2 3 4 5 6 a b)

(set 'aList '("hello" "world"))     ("hello" "world")

(append aList '("here" "I am"))     ("hello" "world" "here" "I am")

二つ目の形式では、append はアレイに対して作用します:
In the second form append works on arrays:

(set 'A (array 3 2 (sequence 1 6)))
 ((1 2) (3 4) (5 6))
(set 'B (array 2 2 (sequence 7 10)))
 ((7 8) (9 10))

(append A B)
 ((1 2) (3 4) (5 6) (7 8) (9 10))

(append B B B)
 ((7 8) (9 10) (7 8) (9 10) (7 8) (9 10))

三番目の形式では、append は文字列に作用します。 str-n の文字列が一つの新しい文字列に結合されて返ります。
In the third form, append works on strings. The strings in str-n are concatenated into a new string and returned.

(set 'more " how are you")        " how are you"

(append "Hello " "world," more)   "Hello world, how are you"

append はゼロを含むバイナリ文字列を操作するのにも適しています。 関数 string なら、ゼロのバイトで文字列を切ってしまうからです。
append is also suitable for processing binary strings containing zeroes. The string function would cut off strings at zero bytes.

結合する文字や文字列を指定するには、関数 join が使えます。 引数の文字列への型変換と結合を一回で済ますには、関数 string を使ってください。
Linkage characters or strings can be specified using the join function. Use the string function to convert arguments to strings and append in one step.

変更を目的とする既存のリストや文字列の結合には(訳注:つまり、副作用が必要な時)、関数 extendpush を使ってください。
Use the functions extend and push to append to an existing list or string modifying the target.



append-file

syntax: (append-file str-filename str-buffer)

write-file のように動作しますが、str-filename のファイルが存在する時は、str-buffer の内容を追加します。 ファイルが存在しない時には、それを作ります(この場合、append-filewrite-file と同じ動作)。 この関数の戻り値は、書き込んだバイト数です。
Works similarly to write-file, but the content in str-buffer is appended if the file in str-filename exists. If the file does not exist, it is created (in this case, append-file works identically to write-file). This function returns the number of bytes written.

失敗した時、関数は nil を返します。ファイルで使っている時のエラー情報には、sys-error も使えます。
On failure the function returns nil. For error information, use either sys-error when used on files.

(write-file "myfile.txt" "ABC") 
(append-file "myfile.txt" "DEF")

(read-file "myfile.txt")   "ABCDEF"

append-file は、str-file-namehttp://file:// の URL を取ることができます。 接頭語が、http:// の場合、append-file は、ちょうど "Pragma: append\r\n" のヘッダー・オプションを持つ put-url のように動作し、追加のパラメータにも同じものが使えます。 オプションの "Pragma: append\r\n" は自動的に与えられます。
append-file can take a http:// or file:// URL in str-file-name. In case of the http:// prefix , append-file works exactly like put-url with "Pragma: append\r\n" in the header option and can take the same additional parameters. The "Pragma: append\r\n" option is supplied automatically.

(append-file "http://asite.com/message.txt" "More message text.")

この message.txt ファイルは、リモート位置の http://asite.comstr-buffer の内容を追加されます。 もし、ファイルが存在しないなら、作成されます。 このモードにおいて、append-file はリモート newLISP サーバー・ノードにファイルを転送するためにも使えます。
The file message.txt is appended at a remote location http://asite.com with the contents of str-buffer. If the file does not yet exist, it will be created. In this mode, append-file can also be used to transfer files to remote newLISP server nodes.

read-filewrite-file も見てください。
See also read-file and write-file.



apply

syntax: (apply func list [int-reduce])
syntax: (apply func)

引数の listfunc(組込関数、ユーザ定義関数、ラムダ式)の内容を適用します(訳注:引数の list の括弧を外して、func に与えるのと同等)。 関数や演算子が引数に対して標準的な評価を行ないます。
Applies the contents of func (primitive, user-defined function, or lambda expression) to the arguments in list. Only functions and operators with standard evaluation of their arguments can be applied.

第二構文の apply は引数を取らない関数に使います。
In the second syntax apply is used on functions without any arguments.

(apply + '(1 2 3 4))                    10
(set 'aList '(3 4 5))                   (3 4 5)
(apply * aList)                         60
(apply sqrt '(25))                      5
(apply (lambda (x y) (* x y)) '(3 4))   12

int-reduce パラメータはオプションで、関数 func の受け取る要素数が入ります。 この場合、func は前の結果を第一引数として取り、受け取る残りの要素を list から(左から順に)取ることを繰り返します。 例えば、op が二つの引数を取るなら、こうなります:
The int-reduce parameter can optionally contain the number of arguments taken by the function in func. In this case, func will be repeatedly applied using the previous result as the first argument and taking the other arguments required successively from list (in left-associative order). For example, if op takes two arguments, then:

(apply op '(1 2 3 4 5) 2)

;; is equivalent to

(op (op (op (op 1 2) 3) 4) 5)

;; find the greatest common divisor 
;; of two or more integers 
;; note that newLISP already has a gcd function

(define (gcd_ a b)
    (let (r (% b a))
        (if (= r 0) a (gcd_ r a))))

(define-macro (my-gcd)
    (apply gcd_ (map eval (args)) 2))

(my-gcd 12 18 6)     6
(my-gcd 12 18 6 4)   2

最後の例は、apply畳み込み(縮約) を使って、引数二つの関数が一度に複数の引数を取れる様子を示しています。 記しておきますが、これは組込 gcd でも可能です。(訳注:組込gcd は二つ以上の整数値の最大公約数を返します。)
The last example shows how apply's reduce functionality can be used to convert a two-argument function into one that takes multiple arguments. Note, that a built-in gcd is available.

apply は、dotimescase のようにいくつかの引数だけを評価するような特殊形式 を持つものではなく、引数を全て評価する関数や演算子に対して使うべきです。 そうしないと、その関数は失敗します。
apply should only be used on functions and operators that evaluate all of their arguments, not on special forms like dotimes or case, which evaluate only some of their arguments. Doing so will cause the function to fail.

(訳例:Common Lisp では orandapply できませんが、newLISP では可能です。
> (apply or '(nil nil 1))
1
> (apply and '(1 2 3))
3
> 


args

syntax: (args)
syntax: (args int-idx-1 [int-idx-2 ... ])

現在評価中の define のラムダ式や define-macro のラムダ・マクロ式に渡された引数の内、束縛されていない引数全てをリストとして扱えます。 つまり、現関数または現マクロで、ローカル変数に束縛された後に残った引数のみが利用できるわけです。 関数 args は、パラメータ数が可変の関数やマクロの定義に役立ちます。
Accesses a list of all unbound arguments passed to the currently evaluating define, define-macro lambda, or lambda-macro expression. Only the arguments of the current function or macro that remain after local variable binding has occurred are available. The args function is useful for defining functions or macros with a variable number of parameters.

args は、変数捕捉の危険を避ける安全なマクロを定義するのにも使えます。 define-macro を見てください。
args can be used to define hygienic macros that avoid the danger of variable capture. See define-macro.

(define-macro (print-line)
    (dolist (x (args))
        (print x "\n")))
                        
(print-line "hello" "World")

この例は各引数の後に改行を出力します。 このマクロは組込関数 println の効果を真似ています。
This example prints a line-feed after each argument. The macro mimics the effect of the built-in function println.

第二構文では、args は一つ以上のインデックス(int-idx-n)を取ることができます。
In the second syntax, args can take one or more indices (int-idx-n).

(define-macro (foo)
    (print (args 2) (args 1) (args 0)))

(foo x y z) 
zyx 

(define (bar)
	(args 0 2 -1))

(bar '(1 2 (3 4)))   4

関数 foo は引数の順序を逆にして出力します。 関数 bar では、入れ子リストにアクセスするために複数のインデックスを使った args を示しています。
The function foo prints out the arguments in reverse order. The bar function shows args being used with multiple indices to access nested lists.

(args) には、現関数や現マクロの局所変数として束縛されていない引数のみが入ることを忘れないでください:
Remember that (args) only contains the arguments not already bound to local variables of the current function or macro:

(define (foo a b) (args))
  
(foo 1 2)         ()
                 
(foo 1 2 3 4 5)   (3 4 5)

最初の例では、引数が二つの局所変数 ab に束縛されるので、空リストが返ります。 二番目の例は、(最初の例と同様)最初の二つの引数が束縛され、三つの引数が残り、args で返される様子を示します。
In the first example, an empty list is returned because the arguments are bound to the two local symbols, a and b. The second example demonstrates that, after the first two arguments are bound (as in the first example), three arguments remain and are then returned by args.

(args) は組込やユーザ定義関数の呼び出しに引数として渡すことができますが、マクロの呼び出しには引数として渡すべきではありません、 その場合、(args) は評価されず、結果として、新たなマクロ環境で誤った内容を持つことになります。
(args) can be used as an argument to a built-in or user-defined function call, but it should not be used as an argument to another macro, in which case (args) would not be evaluated and would therefore have the wrong contents in the new macro environment.



array

syntax: (array int-n1 [int-n2 ... ] [list-init])

int-n1 個の要素のアレイを作成し、オプションで list-init の内容に初期化できます。 16次元までの多次元アレイを指定できます。(訳注:初期化できるのが 16 次元まで)
Creates an array with int-n1 elements, optionally initializing it with the contents of list-init. Up to sixteen dimensions may be specified for multidimensional arrays.

newLISP の内部では、一次元アレイの要素群を使って、多次元アレイを作ります。 大規模リストにおけるランダム要素指定があまりに遅くなる時はいつでも、newLISP のアレイを使うべきです。 全てのリスト関数がアレイに使えるわけではありません。 詳細は、リスト の章を見てください。
Internally, newLISP builds multidimensional arrays by using arrays as the elements of an array. newLISP arrays should be used whenever random indexing into a large list becomes too slow. Not all list functions may be used on arrays. For a more detailed discussion, see the chapter on arrays.

(array 5)                   (nil nil nil nil nil)

(array 5 (sequence 1  5))   (1 2 3 4 5)

(array 10 '(1 2))           (1 2 1 2 1 2 1 2 1 2)

いかなる型のオブジェクトでも、アレイを初期化できます。 もし、初期化用リストの要素がアレイの要素より少なければ、アレイの全要素が初期化されるまで、リストが繰り返し使われます。
Arrays can be initialized with objects of any type. If fewer initializers than elements are provided, the list is repeated until all elements of the array are initialized.


(set 'myarray (array 3 4 (sequence 1 12)))
 ((1 2 3 4) (5 6 7 8) (9 10 11 12))

アレイの操作とアクセスには、リストを操作する関数とほとんど同じものが使われます:
Arrays are modified and accessed using most of the same functions used for modifying lists:

(setf (myarray 2 3) 99)  99)
myarray  ((1 2 3 4) (5 6 7 8) (9 10 11 99))

(setf (myarray 1 1) "hello")   "hello"

myarray  ((1 2 3 4) (5 "hello" 7 8) (9 10 11 99))

(setf (myarray 1) '(a b c d))  (a b c d)
myarray  ((1 2 3 4) (a b c d) (9 10 11 99))

(nth 1 myarray)      (a b c d)  ; access a whole row
                    
;; use implicit indexing and slicing on arrays
                    
(myarray 1)      (a b c d)
                    
(myarray 0 -1)   4

(2 myarray)      ((9 10 11 99)) 

(-3 2 myarray)   ((1 2 3 4) (a b c d)) 

行全体を置き換える際は、アレイを使ってするよう注意すべきです。(訳注;上記例ではリストを使っているので、置き換え後の myarray が (アレイ リスト アレイ) になっている)
Care must be taken to use an array when replacing a whole row.

アレイからリストへの変換には、array-list が使えます:
array-list can be used to convert arrays back into lists:

(array-list myarray)   ((1 2 3 4) (a b c d) (1 2 3 99))

リストをアレイに戻すには、リストに flat を適用します:
To convert a list back into an array, apply flat to the list:

(set 'aList '((1 2) (3 4)))              ((1 2) (3 4))

(set 'aArray (array 2 2 (flat aList)))   ((1 2) (3 4))

式がアレイかどうかをチェックするには、関数 array? が使えます:
The array? function can be used to check if an expression is an array:

(array? myarray)                true
                               
(array? (array-list myarray))   nil

関数 sourcesave を使ってアレイを直列化シリアライズすると、アレイを生成するために必要な array 宣言文が生成されたコードに含まれます。 この方法により、save を使って保存する時や source を使ってソース文字列を生成する時、アレイを含む変数が正しく直列化シリアライズされます。
When serializing arrays using the function source or save, the generated code includes the array statement necessary to create them. This way, variables containing arrays are correctly serialized when saving with save or creating source strings using source.

(set 'myarray (array 3 4 (sequence 1 12)))

(save "array.lsp" 'myarray)

;; contents of file arraylsp ;;

(set 'myarray (array 3 4 (flat '(
  (1 2 3 4) 
  (5 6 7 8) 
  (9 10 11 12)))))


array-list

syntax: (array-list array)

array から変換されたリストを返し、オリジナルのアレイは変わずに、そのまま残ります:
Returns a list conversion from array, leaving the original array unchanged:

(set 'myarray (array 3 4 (sequence 1 12)))
 ((1 2 3 4) (5 6 7 8) (9 10 11 12))

(set 'mylist (array-list myarray))
 ((1 2 3 4) (5 6 7 8) (9 10 11 12))

(list (array? myarray) (list? mylist))
 (true true)


array?

syntax: (array? exp)

exp がアレイかどうかをチェックします:
Checks if exp is an array:

(set 'M (array 3 4 (sequence 1 4)))   
 ((1 2 3 4) (1 2 3 4) (1 2 3 4)))


(array? M)                true

(array? (array-list M))   nil


asin

syntax: (asin num-radians)

num-radians の数値の逆正弦関数を計算し、その結果を返します。
Calculates the arcsine function from the number in num-radians and returns the result.

(asin 1)   1.570796327
(sin (asin 1))  1


asinh

syntax: (asinh num-radians)

num-radians の逆双曲線正弦関数を計算します。 ここで、num-radians は双曲線正弦関数値です。
Calculates the inverse hyperbolic sine of num-radians, the value whose hyperbolic sine is num-radians.

(asinh 2)          1.443635475
(sinh (asinh 2))   2


assoc

syntax: (assoc exp-key list-alist)
syntax: (assoc list-exp-key list-alist)

第一構文では、exp-key の値が最初にキー値と一致する要素を含む member-list を、list-alist から検索するのに使われます。 見つかれば、その member-list が返り、見つからなければ、結果は nil になります。
In the first syntax the value of exp-key is used to search list-alist for a member-list whose first element matches the key value. If found, the member-list is returned; otherwise, the result will be nil.

(assoc 1 '((3 4) (1 2)))   (1 2)

(set 'data '((apples 123) (bananas 123 45) (pears 7)))

(assoc 'bananas data)   (bananas 123 45)
(assoc 'oranges data)   nil

assocsetf と一緒に用いて、連想を変更できます。
Together with setf assoc can be used to change an association.

(setf (assoc 'pears data) '(pears 8))

data   ((apples 123) (bananas 123 45) (pears 8))

第二構文では、入れ子になっている高次の連想リスト検索用に、一個以上のキー式を指定できます:
In the second syntax more then one key expressions can be specified to search in nested, multilevel association lists:

(set 'persons '(
    (id001 (name "Anne") (address (country "USA") (city "New York")))
    (id002 (name "Jean") (address (country "France") (city "Paris")))
))

(assoc '(id001 address) persons)  (address (country "USA") (city "New York"))
(assoc '(id001 address city) persons)  (city "New York")

list-aList 中のリストには、デフォルト・ファンクタ として解釈されるコンテキストにすることができます。 この方法では、大規模リストが参照で渡され、高速にアクセスでき、メモリ使用量も少なくて済みます:
The list in list-aList can be a context which will be interpreted as its default functor. This way very big lists can be passed by reference for speedier access and less memory usage:

(set 'persons:persons '(
    (id001 (name "Anne") (address (country "USA") (city "New York")))
    (id002 (name "Jean") (address (country "France") (city "Paris")))
))

(define (get-city db id)
    (last (assoc (list id 'address 'city) db ))
)

(get-city persons 'id001)  "New York"

連想リストの置換には、関数 assocsetf と共に使います。 関数 lookup を使えば、連想検索と要素取り出しを一度にできます。
For making replacements in association lists, use the setf together with the assoc function. The lookup function is used to perform association lookup and element extraction in one step.



atan

syntax: (atan num-radians)

num-radians の逆正接を計算し、返します。
The arctangent of num-radians is calculated and returned.

(atan 1)         0.7853981634
(tan (atan 1))   1


atan2

syntax: (atan2 num-Y-radians num-X-radians)

関数atan2 は Y / X の逆正接をラジアンで計算します。 両引数の符号を戻り値の象限の決定に使います。 atan2デカルト座標極座標に変換するのに役立ます。
The atan2 function computes the principal value of the arctangent of Y / X in radians. It uses the signs of both arguments to determine the quadrant of the return value. atan2 is useful for converting Cartesian coordinates into polar coordinates.

(atan2 1 1)                        0.7853981634
(div (acos 0) (atan2 1 1))         2
(atan2 0 -1)                       3.141592654
(= (atan2 1 2) (atan (div 1 2)))   true


atanh

syntax: (atanh num-radians)

num-radians の逆双曲線正接を計算します。 ここで、num-radians は双曲線正接値です。 もし、num-radians の絶対値が 1 より大きいなら、atanhNaN を返します。 1 ならば、atanh は無限大を返します。
Calculates the inverse hyperbolic tangent of num-radians, the value whose hyperbolic tangent is num-radians. If the absolute value of num-radians is greater than 1, atanh returns NaN; if it is equal to 1, atanh returns infinity.

(atanh 0.5)  0.5493061443
(tanh (atanh 0.5))  0.5
(atanh 1.1)  NaN
(atanh 1)  inf


atom?

syntax: (atom? exp)

exp の値がアトムなら、true を返し、それ以外は nil を返します。 式の評価結果が nil、true、整数、浮動小数点数、文字列、シンボル、組込ならば、その式はアトムです。 リスト、ラムダ式、ラムダ・マクロ式、クォート式はアトムではありません。
Returns true if the value of exp is an atom, otherwise nil. An expression is an atom if it evaluates to nil, true, an integer, a float, a string, a symbol or a primitive. Lists, lambda or lambda-macro expressions, and quoted expressions are not atoms.

(atom? '(1 2 3))       nil
(and (atom? 123)
     (atom? "hello")
     (atom? 'foo))     true
(atom? ''foo)          nil


base64-dec

syntax: (base64-dec str)

strBASE64 文字列をデコードします。 str が有効な BASE64 文字列かどうかは、検査されないことに注意してください。 デコードされた文字列が返ります。
The BASE64 string in str is decoded. Note that str is not verified to be a valid BASE64 string. The decoded string is returned.

(base64-dec "SGVsbG8gV29ybGQ=")   "Hello World"

エンコードするには、関数 base64-enc を使ってください。
For encoding, use the base64-enc function.

newLISP の BASE64 処理は、Unix curl ユーティリティで見つかるルーチンに由来していて、RFC 4648 標準に準拠しています。
newLISP's BASE64 handling is derived from routines found in the Unix curl utility and conforms to the RFC 4648 standard.



base64-enc

syntax: (base64-enc str [bool-flag])

str の文字列が BASE64 フォーマットにエンコードされます。 このフォーマットは、3 * 8 = 24 の入力ビット列を 4 * 8 = 32 出力ビット列にエンコードします。 出力ビット列の各8ビットは入力文字列からの6ビットに相当します。 この6ビットは、文字 A–Z と a–z 数字 0–9、そして、キャラクタ +(プラス記号)と /(スラッシュ)からなる 64 語にエンコードされます。 =(等号)は、置き換えで使われなかった3,4バイト目を埋めるために使われます。 この関数は、バイナリ・データを出力可能なキャラクタに変換する助けとなります。
The string in str is encoded into BASE64 format. This format encodes groups of 3 * 8 = 24 input bits into 4 * 8 = 32 output bits, where each 8-bit output group represents 6 bits from the input string. The 6 bits are encoded into 64 possibilities from the letters A–Z and a–z; the numbers 0–9; and the characters + (plus sign) and / (slash). The = (equals sign) is used as a filler in unused 3- to 4-byte translations. This function is helpful for converting binary content into printable characters.

オプションの引数 bool-flag が無い時、空文字列 """====" にコード化されます。 bool-flagtrue に評価されると、空文字列 """" になります。 どちらの変換物も base64-dec でデコードすると、"" になります。
Without the optional bool-flag parameter the empty string "" is encoded into "====". If bool-flag evaluates to true, the empty string "" is translated into "". Both translations result in "" when using base64-dec.

エンコード文字が返ります。
The encoded string is returned.

BASE64 エンコードは、バイナリ・データをエンコードしてテキスト・ベースのメッセージに含める多くのインターネット・プロトコルで使われています(例えば、XML-RPC)。
BASE64 encoding is used with many Internet protocols to encode binary data for inclusion in text-based messages (e.g., XML-RPC).

(base64-enc "Hello World")   "SGVsbG8gV29ybGQ="

(base64-enc "")              "===="
(base64-enc "" true)         ""

base64-enc は、長いBASE64シーケンス中に改行(CR/LPペア)を挿入できないことに注意してください。 その代わりに、純粋な BASE64 エンコード文字列を返します。
Note that base64-enc does not insert carriage-return/line-feed pairs in longer BASE64 sequences but instead returns a pure BASE64-encoded string.

デコードするには、関数 base64-dec を使います。
For decoding, use the base64-dec function.

newLISP の BASE64 処理は、Unix curl ユーティリティで見つかるルーチンに由来していて、RFC 4648 標準に準拠しています。
newLISP's BASE64 handling is derived from routines found in the Unix curl utility and conforms to the RFC 4648 standard.



bayes-query

syntax: (bayes-query list-L context-D [bool-chain [bool-probs]])

(訳注:訳者は、この手の事情に疎いので、 ベイズの定理ベイズ推定ベイズ確率マルコフ連鎖等をご一読の上、原文をお読み頂くことを強くお薦めします。)
トークンリスト (list-L) と学習辞書 (context-D) を取り、一つのカテゴリ (A または Mc) 対カテゴリ (B) か他のすべてのカテゴリ (Mi) に対する結合確率のリストを返します。 list-L の全てのトークンは context-D に見出されるべきです。 デフォルトの R.A. Fisher 逆カイ二乗法 モードを使う時、存在しないトークンは全てのカテゴリでの等確率へと結果を歪曲するでしょう。
Takes a list of tokens (list-L) and a trained dictionary (context-D) and returns a list of the combined probabilities of the tokens in one category (A or Mc) versus a category (B) or against all other categories (Mi). All tokens in list-L should occur in context-D. When using the default R.A. Fisher inverse Chi²  mode, nonexistent tokens will skew results toward equal probability in all categories.

bool-chaintrue にして Chain Bayesian モードを使った時、存在しないトークンは結果に如何なる影響も持ちません。 オプションの最後のフラグ bool-probs は、頻度もしくは確率値がデータ・セットに使われるかどうかを示します。 普通、関数bayes-train がデータ・セットの頻度を生成するのに使われます。
Non-existing tokens will not have any influence on the result when using the true Chain Bayesian mode with bool-chain set to true. The optional last flag, bool-probs, indicates whether frequencies or probability values are used in the data set. The bayes-train function is typically used to generate a data set's frequencies.

トークンは文字列かシンボルです。 文字列が使われたなら、context-D 上で検索される前にアンダースコアが前に付けられます。 context-D の頻度生成に bayes-train を使えば、アンダースコアは学習過程で自動的に付加されます。
Tokens can be strings or symbols. If strings are used, they are prepended with an underscore before being looked up in context-D. If bayes-train was used to generate context-D's frequencies, the underscore was automatically prepended during the learning process.

bayes-querybool-probs に指定されたフラグ次第で、確率を合成する R. A. Fisher 逆カイ二乗法Chain Bayesian 法のどちらかを使います。 bool-probs にフラグが無いか nil の時、デフォルトで確率を合成する逆カイ二乗法が使われます。 bool-probstrue の時は、Chain Bayesian 法が使われます。
Depending on the flag specified in bool-probs, bayes-query employs either the R. A. Fisher inverse Chi² method of compounding probabilities or the Chain Bayesian method. By default, when no flag or nil is specified in bool-probs, the inverse Chi² method of compounding probabilities is used. When specifying true in bool-probs, the Chain Bayesian method is used.

逆カイ二乗法が使われるなら、異なる学習セットのカテゴリのトークンの全数は、同じか、同程度あるべきです。 カテゴリ中の頻度が不均衡なら、結果は歪曲されるでしょう。
If the inverse Chi² method is used, the total number of tokens in the different training set's categories should be equal or similar. Uneven frequencies in categories will skew the results.

AB の二つのカテゴリに対して、bayes-query は次の公式を使います:
For two categories A and B, bayes-query uses the following formula:

p(A|tkn) = p(tkn|A) * p(A) / ( p(tkn|A) * p(A) + p(tkn|B) * p(B) )

N カテゴリなら、次の公式に一般化します:
For N categories, the formula can be generalized to:

p(Mc|tkn) = p(tkn|Mc) * p(Mc) / sum-i-N( p(tkn|Mi) * p(Mi) )

確率(p(B) と一緒の p(Mi) または p(A))は、ベイズの事前確率を表します。 p(Mc|tkn)p(A|tkn) はカテゴリやモデルの ベイズの事後確率 です。 この単純 ベイズ公式は成り立ちますが、異なるカテゴリの依存関係を織り込めません。
The probabilities (p(Mi) or p(A), along with p(B)) represent the Bayesian prior probabilities. p(Mc|tkn) and p(A|tkn) are the posterior Bayesian probabilities of a category or model. This naive Bayes formula does nor take into account dependencies between different categories.

逆カイ二乗法か Chain Bayesian 法で、事前確率の扱いが異なります。 Chain Bayesian 法では、一トークン計算からの事後確率で次の計算の事前確率を得ます。 デフォルトの逆カイ二乗法では事前確率を連鎖として伝えませんが、確率は逆カイ二乗法を使って合成されます。
Priors are handled differently, depending on whether the inverse Chi² or the Chain Bayesian method is used. In Chain Bayesian mode, posteriors from one token calculation get the priors in the next calculation. In the default inverse Chi² method, priors are not passed on via chaining, but probabilities are compounded using the inverse Chi² method.

Chain Bayes モードでは、一カテゴリのゼロ頻度のトークンはカテゴリの確率を事実上 0(ゼロ)にします。 これはまた、結果として全ての事後や事前を 0 へセットし、完全に抑えられたカテゴリをもたらします。 全てのカテゴリに 0 確率の結果をもたらす質問クエリNaN 値を引き起こします。
In Chain Bayes mode, tokens with zero frequency in one category will effectively put the probability of that category to 0 (zero). This also causes all posterior priors to be set to 0 and the category to be completely suppressed in the result. Queries resulting in zero probabilities for all categories yield NaN values.

デフォルトの逆カイ二乗法は 0 頻度に敏感ではありませんし、まだ、そのトークンの低確率を持続します。 これは ベイズ統計 を使う自然言語処理において重要な特徴です。 五つの異なる言語の集大成 のカテゴリが学習されているけれど、一カテゴリのいくつかの単語が他に存在しない時のことを考えてください。 純粋な Chain Bayesian 法が使われる時、文章は、その正しいカテゴリに分類されません。 なぜなら、ちょうど一つのトークンのゼロ・カウントが、その所属するカテゴリへの分類を事実上、拒むからです。
The default inverse Chi² method is less sensitive about zero frequencies and still maintains a low probability for that token. This may be an important feature in natural language processing when using Bayesian statistics. Imagine that five different language corpus categories have been trained, but some words occurring in one category are not present in another. When the pure Chain Bayesian method is used, a sentence could never be classified into its correct category because the zero-count of just one word token could effectively exclude it from the category to which it belongs.

一方で、Chain Bayesian 法はデータの具体的な比率の正確な結果を提供します。 自然言語データで Chain Bayesian モードを使う時、最初に全てのゼロ頻度が学習された辞書から取り除かれます。
On the other hand, the Chain Bayesian method offers exact results for specific proportions in the data. When using Chain Bayesian mode for natural language data, all zero frequencies should be removed from the trained dictionary first.

bayes-query の戻り値は、各カテゴリの一つの確率値のリストです。 次に二つの事例を示します: 最初はデフォルトの逆カイ二乗モード、二つ目は Chain Bayesian 法によるデータセット処理。
The return value of bayes-query is a list of probability values, one for each category. Following are two examples: the first for the default inverse Chi² mode, the second for a data set processed with the Chain Bayesian method.


R.A. Fisher inverse Chi² method(R.A. Fisher 逆カイ二乗法)

次の例で、二つのデータ・セットはグーテンベル・グプロジェクト(訳注;日本でいう青空文庫に相当)の本です。 私たちは、作家が違えば、使われる単語の頻度が異なると推測し、文章が一方の作家が書いたものか、それとも他方の作家のものか、可能性の高い方を決定したいと思います。 似たような方法が、しばしば、スパムか合法的なメールかの識別に使われます。
In the following example, the two data sets are books from Project Gutenberg. We assume that different authors use certain words with different frequencies and want to determine if a sentence is more likely to occur in one or the other author's writing. A similar method is frequently used to differentiate between spam and legitimate email.

;; from Project Gutenberg: http://www.gutenberg.org/catalog/
;; The Adventures of Sherlock Holmes - Sir Arthur Conan Doyle

(bayes-train (parse (lower-case (read-file "Doyle.txt")) 
                    "[^a-z]+" 0) '() 'DoyleDowson)

;; A Comedy of Masks - Ernest Dowson and Arthur Moore

(bayes-train '() (parse (lower-case (read-file "Dowson.txt")) 
                    "[^a-z]+" 0) 'DoyleDowson)

(save "DoyleDowson.lsp" 'DoyleDowson)

二つの学習セットがロードされ、トークンに分解され、関数 bayes-train で処理されます。 最後に、関数bayes-query で使えるように、DoyleDowson 辞書をファイルにセーブします。
The two training sets are loaded, split into tokens, and processed by the bayes-train function. In the end, the DoyleDowson dictionary is saved to a file, which will be used later with the bayes-query function.

次のコードは、文章を DoyleDowson に分類するのに、bayes-query がどのように使われるかを示します。
The following code illustrates how bayes-query is used to classify a sentence as Doyle or Dowson:

(load "DoyleDowson.lsp")
(bayes-query (parse "he was putting the last touches to a picture") 
    'DoyleDowson)
 (0.0359554723158327 0.964044527684167) 

(bayes-query (parse "immense faculties and extraordinary powers of observation") 
    'DoyleDowson)
 (0.983569359827141 0.0164306401728594) 

質問クエリは、最初の文章が Dowson の文章で、二番目が Doyle の文章であることを正しく識別しています。
The queries correctly identify the first sentence as a Dowson sentence, and the second one as a Doyle sentence.


Chain Bayesian method

二番目の例は、ベイズ統計学の紹介文献にしばしば見られます。 前もって処理されたデータ・セットのデータ上で bayes-query を使う Chain Bayesian法 を示しています:
The second example is frequently found in introductory literature on Bayesian statistics. It shows the Chain Bayesian method of using bayes-query on the data of a previously processed data set:

(set 'Data:test-positive '(8 18))
(set 'Data:test-negative '(2 72))
(set 'Data:total '(10 90))

ある病気は、人口の10%で発生します。 この病気を検査するために開発されたテストは、健康な人の 20%に偽陽性反応と病気な人の 20%に偽陰性反応を生じます。 テストが陽性で病気に感染している確率はいくらでしょうか?
(訳注:上記例は、感染者10人のグループと非感染者90人のグループの二つがあり、感染者の内、8人が検査に陽性、2人が陰性。 そして、非感染者の内、18人が検査に陽性、72人が陰性。 という設定)
A disease occurs in 10 percent of the population. A blood test developed to detect this disease produces a false positive rate of 20 percent in the healthy population and a false negative rate of 20 percent in the sick. What is the probability of a person carrying the disease after testing positive?

(bayes-query '(test-positive) Data true)
 (0.3076923077 0.6923076923)

(bayes-query '(test-positive test-positive) Data true)
 (0.64 0.36)

(bayes-query '(test-positive test-positive test-positive) Data true)
 (0.8767123288 0.1232876712)

bayes-query を正しく動作させるためには、イベント間の統計上の独立を前提にベイズの公式を使用するよう、注意してください。
Note that the Bayesian formulas used assume statistical independence of events for the bayes-query to work correctly.

この例は、病気であると確実に分類される前に、何回か陽性をテストしなければならないことを示しています。
(訳注:3回検査して全部陽性なら、9割弱の確率で感染しているということ)
The example shows that a person must test positive several times before they can be confidently classified as sick.

同じ例の計算に R.A. Fisher Chi² 法を使えば、区別し難い結果となります。
Calculating the same example using the R.A. Fisher Chi² method will give less-distinguished results.


Specifying probabilities instead of counts

データは、しばしば既に確率値として利用できるようになっていて、それらを頻度に戻す追加の作業が要求されます。 最後の例では、データは初めからパーセンテージで定義されています。 追加のオプション bool-probs フラグは確率の直接入力を許可し、最大の効果を得るために Chain Bayesian モードで使うべきです:
Often, data is already available as probability values and would require additional work to reverse them into frequencies. In the last example, the data were originally defined as percentages. The additional optional bool-probs flag allows probabilities to be entered directly and should be used together with the Chain Bayesian mode for maximum performance:

(set 'Data:test-positive '(0.8 0.2))
(set 'Data:test-negative '(0.2 0.8))
(set 'Data:total '(0.1 0.9))

(bayes-query '(test-positive) Data true true)
 (0.3076923077 0.6923076923)

(bayes-query '(test-positive test-positive) Data true true)
 (0.64 0.36)

(bayes-query '(test-positive test-positive test-positive) Data true true)
 (0.8767123288 0.1232876712)

予想されるように、結果は頻度の時と同じ確率になります。
As expected, the results are the same for probabilities as they are for frequencies.



bayes-train

syntax: (bayes-train list-M1 [list-M2 ... ] sym-context-D)

トークンのジョイント・セットから、単語 (M1, M2–) のリストを一つ以上取ります。 newLISP上では、トークンはシンボルか、文字列になります(他のデータ・タイプは無視されます)。 トークンは sym-context-D の共通辞書上に置かれ、各カテゴリ Mi における各トークンの頻度がカウントされます。 コンテキストが、まだ存在しない時は、それを示す必要があります(訳注:つまり、sym-context-Dは必ず指定しなければならないということ)。
Takes one or more lists of tokens (M1, M2—) from a joint set of tokens. In newLISP, tokens can be symbols or strings (other data types are ignored). Tokens are placed in a common dictionary in sym-context-D, and the frequency is counted for each token in each category Mi. If the context does not yet exist, it must be quoted.

カテゴリM は分類可能なトークンの列のデータ・モデルを示します(bayes-query 参照)。 D の各トークンは各カテゴリでのそのトークンの頻度のリストを含むコンテキストで参照可能なシンボルです。 トークン文字列はシンボルに変換される前に、先頭に _(アンダースコア)が付加されます。 total という名前のシンボルが生成され、各カテゴリの(訳注:トークンの)全数の入ります。 シンボルtotal は、カテゴリMi で渡されるシンボルにはなりません。
The M categories represent data models for which sequences of tokens can be classified (see bayes-query). Each token in D is a content-addressable symbol containing a list of the frequencies for this token within each category. String tokens are prepended with an _ (underscore) before being converted into symbols. A symbol named total is created containing the total of each category. The total symbol cannot be part of the symbols passed as an Mi category.

(訳例:つまり、total というシンボルをトークンにすると、まずいことになります。
> (bayes-train '(A A B C C) '(A B B C C total C) 'L)
(5 8)
> L:A
(2 1)
> L:B
(1 2)
> L:C
(2 3)
> L:total
(5 8)
しかし、文字列を使えば、回避できます。
> (bayes-train '("A" "A" "B" "C" "C") '("A" "B" "B" "C" "C" "total" "C") 'L)
(5 7)
> L:_A
(2 1)
> L:_B
(1 2)
> L:_C
(2 3)
> L:_total
(0 1)

この関数は、異なるカテゴリやモデルで見つかったトークン頻度のリストを返します。
The function returns a list of token frequencies found in the different categories or models.

; count the symbols in two lists
(bayes-train '(A A B C C) '(A B B C C C) 'L)   (5 6)

L:A       (2 1)
L:B       (1 2)
L:C       (2 3)
L:total   (5 6)

; count words in three lists
(bayes-train '("one" "two" "two" "three")
             '("three" "one" "three") 
             '("one" "two" "three") 'S)       
 (4 3 3)

; inspect the symbols created
S:_one     (1 1 1)
S:_two     (2 0 1)
S:_three   (1 2 1)
S:total    (4 3 3)

一番目の例は二つのシンボル・リストによる学習を示しています。 二番目の例は文字列による学習で、どのように _ が付加されるかを示しています。
The first example shows training with two lists of symbols. The second example illustrates how an _ is prepended when training with strings.

bayes-train は、アンダースコアを付加することで文字列からシンボルを生成します。これは、ハッシュが作られる時の方法と同じで、bayes-train のシンボルが入ったコンテキストはハッシュのように使えます:
bayes-train creates symbols from strings prepending an underscore character. This is the same way hashes are created and contexts populates with symbols by bayes-train can be used like hashes:

; use a bayes-trained context namespace like a hash dictionary

(S "two")    (2 0 1)
(S "three")  (1 2 1)

; translate the namespace into an association list

(S)  (("one" (1 1 1)) ("three" (1 2 1)) ("two" (2 0 1)))

これらの例は、デモ用であることに注意してください。 実際、学習セットは特に自然言語モデルの学習のような時に、千から万単位の単語を持ちます。 しかし、シンボルの頻度が既に知られている割合で記述されている時は、小さいデータセットが使われます。 このような場合は、関数 bayes-train を使わずに、きっちりとしたモデル・データ・セットを記述した方が良いでしょう:
Note that these examples are just for demonstration purposes. In reality, training sets may contain thousands or millions of words, especially when training natural language models. But small data sets may be used when the frequency of symbols just describe already-known proportions. In this case, it may be better to describe the model data set explicitly, without the bayes-train function:

(set 'Data:tested-positive '(8 18))
(set 'Data:tested-negative '(2 72))
(set 'Data:total '(10 90))

最後のデータは関数 bayes-query を記述するために、ベイジアン・ネットワーク の紹介文や本で、よく使われる例から取っています。
The last data are from a popular example used to describe the bayes-query function in introductory papers and books about bayesian networks.

学習は実際にある学習したコンテキストとそれと同数のカテゴリ上で、bayes-train を使って異なるステージで行われます。 新シンボルが付加され、カウント値と全数が正しく更新されます。
Training can be done in different stages by using bayes-train on an existing trained context with the same number of categories. The new symbols will be added, then counts and totals will be correctly updated.

複数のバッチによる学習は、最初、トークン化が必要な大きなテキスト集や文献で必要になるかもしれません。 これらの集合体は複数のステージで bayes-train に与えることで、小さな部品としてのトークン化が可能です、集まりの無い空のリストを与えられると、カテゴリの学習は不自然になります:
Training in multiple batches may be necessary on big text corpora or documents that must be tokenized first. These corpora can be tokenized in small portions, then fed into bayes-train in multiple stages. Categories can also be singularly trained by specifying an empty list for the absent corpus:

(bayes-train shakespeare1 '() 'data)
(bayes-train shakespeare2 '() 'data)
(bayes-train '() hemingway1 'data)
(bayes-train '() hemingway2 'data)
(bayes-train shakepeare-rest hemingway-rest 'data)

bayes-train は、単語のカウントと全数を正しく更新します。
bayes-train will correctly update word counts and totals.

bayes-trainMAIN でない他のコンテキストで使うには、関数 context によって、MAIN 上に前もって学習用コンテキストを用意しておく必要があります。
Using bayes-train inside a context other than MAIN requires the training contexts to have been created previously within the MAIN context via the context function.

bayes-train は、関数bayes-query に役立つだけでなく、汎用的なカウント関数としても使えます。 例えば、頻度の結果はカテゴリ中のアイテムの比例分布の帰無仮説に対して、prob-chi2 を使った解析を可能にします。
bayes-train is not only useful with the bayes-query function, but also as a function for counting in general. For instance, the resulting frequencies could be analyzed using prob-chi2 against a null hypothesis of proportional distribution of items across categories.



begin

syntax: (begin body)

関数begin は、式のブロックをグループ化して使うことができます。 body 中の式は順次評価され、body の最後の式の値を返します。
The begin function is used to group a block of expressions. The expressions in body are evaluated in sequence, and the value of the last expression in body is returned.

(begin
  (print "This is a block of 2 expressions\n")
  (print "================================"))

conddefinedoargsdolistdostringdotimeswhenwhile のような組込関数は本体に複数の式を持つことができますが、if 式では begin がよく使われます。
Some built-in functions like cond, define, doargs, dolist, dostring, dotimes, when and while already allow multiple expressions in their bodies, but begin is often used in an if expression.

関数 silentbegin のように動作しますが、戻り値のコンソール出力を抑えます。
The silent function works like begin, but suppresses console output on return.



beta

syntax: (beta cum-a num-b)

ベータ 関数 beta は、ガンマの対数 の関数 gammaln から次のようにして、得られます:(訳注:ベータ関数
The Beta function, beta, is derived from the log Gamma gammaln function as follows:

beta = exp(gammaln(a) + gammaln(b) - gammaln(a + b))

(beta 1 2)   0.5


betai

syntax: (betai num-x num-a num-b)

不完全ベータ 関数 betai は、num-x 上の xベータ 分布 betai の累積確率と等しくなります。 この累積2項分布は、確率 pN 回試行中 k 回または、それ以上の回数が起こるイベントの確率 pev として定義されます:(訳注:不完全ベータ関数
The Incomplete Beta function, betai, equals the cumulative probability of the Beta distribution, betai, at x in num-x. The cumulative binomial distribution is defined as the probability of an event, pev, with probability p to occur k or more times in N trials:

pev = Betai(p, k, N - k + 1)

(betai 0.5 3 8)   0.9453125

例では、0.5 の確率のイベントが 10 回 (8 = 10 - 3 + 1) 中 3 回以上起こる確率を計算しています。 不完全ベータ分散は数学や統計において、様々な関数を得るために使われます。 関数 binomial も見てください。
The example calculates the probability for an event with a probability of 0.5 to occur 3 or more times in 10 trials (8 = 10 - 3 + 1). The incomplete Beta distribution can be used to derive a variety of other functions in mathematics and statistics. See also the binomial function.

(訳例:Lutz氏作(by Lutz)
;; probability of F ratio for df1/df2
;; by Lutz
;;
(define (Lutz-prob-f f df1 df2)
  (let (prob (mul 2 (betai (div df2 (add df2 (mul df1 f))) 
                           (mul 0.5 df2) 
                           (mul 0.5 df1)))) 
    (div (if (> prob 1) (sub 2 prob) prob) 2)
))

;; one-tailed probablity of Student's t
;; by Lutz
;;
(define (Lutz-prob-t t df)
    (let (bta (betai (div (add 1 (div (pow t) df))) (div df 2) 0.5))
        (if  
            (> t 0) (sub 1 (mul 0.5 bta))
            (< t 0) (mul 0.5 bta) 
            0.5)
))
;; 組込prob-t とは
;; (prob-t t df) = (sub 1 (Lutz-prob-t t df))
;; という関係にあります


bigint

syntax: (bigint number)
syntax: (bigint string)

浮動小数点数または整数を大整数に変換します。 浮動小数点数の変化の際は、十進数と二進数間の丸め誤差が生じます。
A floating point or integer number gets converted to big integer format. When converting from floating point, rounding errors occur going back and forth between decimal and binary arithmetic.

引数が文字列の時は、数値を解析して大整数に変換します。
A string argument gets parsed to a number and converted to a big integer.

(bigint 12345)           12345L

(bigint 1.234567890e30)  1234567889999999957361000000000L 

(set 'num 567890)
(bigint num)             567890L

(bigint "-54321")        -54321L
(bigint "123.45")        123L
(bigint "123hello")      123L

このマニュアルの算術精度に制限のない大整数の章も見てください。
See also the manual chapter Big integer, unlimited precision arithmetic



bigint?

syntax: (bigint? number)

数値が大整数かどうかをチェックします。
Check if a number is formatted as a big integer.

(set 'x 12345)
(set 'y 12345L)
(set 'z 123456789012345678901234567890)
(set 'p 1.2345e20)
(set 'q (bigint p))

(bigint? x)   nil
(bigint? y)   true
(bigint? z)   true
(bigint? p)   nil
(bigint? q)   true

このマニュアルの算術精度に制限のない大整数の章も見てください。
See also the manual chapter Big integer, unlimited precision arithmetic



bind !

syntax: (bind list-variable-associations [bool-eval])

list-variable-associations には、シンボルとその値からなる連想リスト(訳注:((シンボル1 連想値1) (シンボル2 連想値2) …) )が入ります。 bind は、全てのシンボルにその連想値をセットします。
list-variable-associations contains an association list of symbols and their values. bind sets all symbols to their associated values.

bool-evaltrue なら、連想値は評価されます:
The associated values are evaluated if the bool-eval flag is true:

(set 'lst '((a (+ 3 4)) (b "hello")))

(bind lst)          "hello"

a     (+ 3 4)
b     "hello"

(bind lst true)     "hello"

a     7

bind の戻り値は最後の連想値です。
The return value of bind is the value of the last association.

bind is often used to bind association lists returned by unify.

(bind (unify '(p X Y a) '(p Y X X)))     a

X     a
Y     a

これは、構造体の仕分けに使えます:
This can be used for de-structuring:

(set 'structure '((one "two") 3 (four (x y z))))
(set 'pattern '((A B) C (D E)))
(bind (unify pattern structure))

A  one
B  "two"
C  3
D  four
E  (x y z)

unify が連想リストを返し、bind がその関連付け(訳注:連想)を束縛します。
unify returns an association list and bind binds the associations.



binomial

syntax: (binomial int-n int-k float-p)

二項分布関数は、イベントが float-p の確率を持ち、各試行で互いに独立である時、 int-nint-k 回起こる確率として定義されます:
The binomial distribution function is defined as the probability for an event to occur int-k times in int-n trials if that event has a probability of float-p and all trials are independent of one another:

binomial = pow(p, k) * pow(1.0 - p, n - k) * n! / (k! * (n - k)!)

ここで、x!x の階乗、pow(x, y)xy 乗です。
where x! is the factorial of x and pow(x, y) is x raised to the power of y.


(binomial 10 3 0.5)   0.1171875

この例では、0.5 の確率のイベントが 10 回中 3 回起こる確率を計算しています。 累積分布については、関数 betai を見てください。
The example calculates the probability for an event with a probability of 0.5 to occur 3 times in 10 trials. For a cumulated distribution, see the betai function.



bits

syntax: (bits int [bool])

int の数値を 1 と 0 の文字列に変換します。 boolnil 以外なら、(訳注:真偽の)リストを返します。
Transforms a number in int to a string of 1's and 0's or a list, if bool evaluates to anything not nil.

文字列で再定義されたビットは、高位から下位への順です。 リスト表現では、1 と 0 が truenil になり、下位から上位への順になります。 これにより、結果の直接的要素指定や結果によるプログラム制御切替が可能になります。
In string representation bits are in high to low order. In list presentation 1's and 0's are represented as true and nil and in order from the lowest to the highest bit. This allows direct indexing and program control switching on the result.

(bits 1234)       "10011010010"

(int (bits 1234) 0 2)  1234

(bits 1234 true)      (nil true nil nil true nil true true nil nil true)

((bits 1234 true) 0)  nil ; indexing of the result

基底 2 で使う intbits の逆関数です。
int with a base of 2 is the inverse function to bits.



syntax: (callback int-index sym-function)
syntax: (callback sym-function str-return-type [str_param_type ...])
syntax: (callback sym-function)

第一単純 callback 構文では、8つまでのパラメータを持てる 16 個 (0 ~ 15) の callback 関数を導入ライブラリとして登録することができます。 関数 callback はユーザ定義関数 sym-function を実行させるための開始アドレスを返します。 次の例で、OpenGL グラフィック・ライブラリ導入時のコールバック関数の使い方を示します:
In the first simple callback syntax up to sixteen (0 to 15) callback functions for up to eight parameters can be registered with imported libraries. The callback function returns a procedure address that invokes a user-defined function in sym-function. The following example shows the usage of callback functions when importing the OpenGL graphics library:

もし、16 個より多いコールバック関数が必要なら、スロットを異なるコールバック関数に再定義する必要があります。
If more than sixteen callback functions are required, slots must be reassigned to a different callback function.

...
(define (draw)
    (glClear GL_COLOR_BUFFER_BIT )
    (glRotated rotx 0.0 1.0 0.0)
    (glRotated roty 1.0 0.0 0.0)
    (glutWireTeapot 0.5)
    (glutSwapBuffers))

(define (keyboard key x y)
    (if (= (& key 0xFF) 27) (exit)) ; exit program with ESC
    (println "key:" (& key 0xFF) " x:" x  " y:" y))

(define (mouse button state x y)
    (if (= state 0)
        (glutIdleFunc 0) ; stop rotation on button press
        (glutIdleFunc (callback 4 'rotation)))
    (println "button: " button " state:" state " x:" x " y:" y))

(glutDisplayFunc (callback 0 'draw))
(glutKeyboardFunc (callback 1 'keyboard))
(glutMouseFunc (callback 2 'mouse))
...

callback で返されるアドレスは Glut ライブラリに登録されます。 上記コードは、newLISP 配布ソースの examples/ ディレクトリにある opengl-demo.lsp ファイルの一部です。 また、newlisp.org/downloads/OpenGL からもダウンロードできます。
The address returned by callback is registered with the Glut library. The above code is a snippet from the file opengl-demo.lsp, in the examples/ directory of the source distribution of newLISP and can also be downloaded from newlisp.org/downloads/OpenGL.

第二拡張 callback 構文では、関数が呼び出される時の戻り値とパラメーター値の型を表わすために型指定子を使います。 第二構文で登録されるコールバック関数は数に制限がありません。 そして、戻り値は呼び出した関数に渡されます。 sym-function のシンボルには、C プログラムから呼び出し可能なコールバック関数として定義された newLISP の関数が入ります。
In the second extanded callback syntax type specifiers are used to describe the functions return and parameter value types when the function is called. An unlimited number of callback functions can be registered with the second syntax, and return values are passed back to the calling function. The symbol in sym-function contains a newLISP defined function used as a callback function callable from a C program.

第三構文では、callbackはそのシンボルに前もって返される C 呼び出し可能アドレスを返します。
In the third syntax callback returns a previously returned C-callable address for that symbol.

第一単純 callback 構文は整数値とポインタのみ扱いますが、拡張構文の callback では callback 関数の出力に渡される単精度と倍精度の浮動小数点数も扱えます。
While the first simple callback syntax only handles integers and pointer values, callback in the expanded syntax can also handle simple and double precision floating point numbers passed in an out of the callback function.

単純及び拡張構文は同じプログラム内に混在できます。
Both the simple and extended syntax can be mixed inside the same program.

次に例には C ライブラリ関数 qsortimport があり、その引数の一つに比較関数のアドレスを取ります。 この場合の比較関数は newLISP で書かれ、導入した qsort の中で呼び出されています:
The following example shows the import of the qsort C library function, which takes as one of it's arguments the address of a comparison function. The comparison function in this case is written in newLISP and called into by the imported qsort function:

; C void qsort(...) takes an integer array with number and width
; of array elements and a pointer to the comparison function
(import "libc.dylib" "qsort" "void" "void*" "int" "int" "void*")

(set 'rlist '(2 3 1 2 4 4 3 3 0 3))
; pack the list into an C readable 32-bit integer array
(set 'carray (pack (dup "ld " 10) rlist))

; the comparison callback function receives pointers to integers
(define (cmp a b) 
    (- (get-int a) (get-int b)))

; generate a C callable address for cmp
(set 'func (callback 'cmp "int" "void*" "void*"))

; sort the carray
(qsort carray 10 4 func)

; unpack the sorted array into a LISP list
(unpack (dup "ld" 10) carray)    (0 1 2 2 3 3 3 3 4 4) 

型指定子には、関数 import で使われるのと同じ文字列タグが使えます。 全てのポインタ型は callback 関数の入出力で、数値として渡されます。 パラメータから異なる精度の数値を取り出すには、関数 get-charget-intget-longget-string が使えます。 バイナリ・バッファや構造体からデータを取り出すには、packunpack を使ってください。
As type specifiers the same string tags can be used as in the import function. All pointer types are passed as numbers in and out of the callback function. The functions get-char, get-int, get-long and get-string can be used to extract numbers of different precision from parameters. Use pack and unpack to extract data from binary buffers and structures.

すでに newLISP には、高速の組込関数 sort があることをお忘れなく。
Note that newLISP as already a fast built-in sort function.



case

syntax: (case exp-switch (exp-1 body-1) [(exp-2 body-2) ... ])

exp-switch の評価結果が 評価されないexp-1, exp-2, – と比較されます。 もし、一致するものが見つかれば、続く body 中の式群が評価されます。 body の最後の式の結果が case 式全体の結果として返ります。
The result of evaluating exp-switch is compared to each of the unevaluated expressions exp-1, exp-2, —. If a match is found, the corresponding expressions in body are evaluated. The result of the last body expression is returned as the result for the entire case expression.

(define (translate n)
  (case n
    (1 "one")
    (2 "two")          
    (3 "three")
    (4 "four")
    (true "Can't translate this")))

(translate 3)    "three"
(translate 10)   "Can't translate this"

この例が示すように、一致するものがなかった時、関数 case 本体の最後式を評価するようにできます。
The example shows how, if no match is found, the last expression in the body of a case function can be evaluated.



catch

syntax: (catch exp)
syntax: (catch exp symbol)

第一構文の catchexp の評価結果か、exp の評価中に実行される throw の引数の評価結果を返します:
In the first syntax, catch will return the result of the evaluation of exp or the evaluated argument of a throw executed during the evaluation of exp:

(catch (dotimes (x 1000) 
  (if (= x 500) (throw x))))   500

この形式は、繰り返しループからの脱出や関数またはブロック式からの早期強制脱出に使えます:
This form is useful for breaking out of iteration loops and for forcing an early return from a function or expression block:

(define (foo x)
   …
  (if condition (throw 123))
    …
  456)

;; if condition is true

(catch (foo p))   123

;; if condition is not true

(catch (foo p))   456

第二構文の catch は、式 exp を評価して結果を symbol に収め、true を返します。 評価中にエラーが発生すれば、catchnil を返してエラー・メッセージを symbol に収めます。 この形式は、エラーが関数の可能性のある出力として予想される場合や、エラーがプログラム実行の一環として扱われる時に有効です。
In the second syntax, catch evaluates the expression exp, stores the result in symbol, and returns true. If an error occurs during evaluation, catch returns nil and stores the error message in symbol. This form can be useful when errors are expected as a normal potential outcome of a function and are dealt with during program execution.

(catch (func 3 4) 'result)   nil
result  
 "ERR: invalid function in function catch : (func 3 4)"

(constant 'func +)           + <4068A6>
(catch (func 3 4) 'result)   true
result                       7

exp の評価中に throw が実行されると、catchtrue を返し、throw の引数が symbol に収められます:
When a throw is executed during the evaluation of exp, catch will return true, and the throw argument will be stored in symbol:

(catch (dotimes (x 100) 
  (if (= x 50) (throw "fin"))) 'result)   true

result   "fin"

関数からの早期脱出や繰り返しループの中断に使えるように、第二構文の catch はエラー捕捉にも使うことができます。 ユーザ定義エラーを起こすためには、関数 throw-error を使います。
As well as being used for early returns from functions and for breaking out of iteration loops (as in the first syntax), the second syntax of catch can also be used to catch errors. The throw-error function may be used to throw user-defined errors.



ceil

syntax: (ceil number)

浮動小数点数 number より大きい最初の整数を返します。
Returns the next highest integer above number as a floating point.

(ceil -1.5)   -1
(ceil 3.4)    4

関数 floor も見てください。
See also the floor function.



change-dir

syntax: (change-dir str-path)

str-path で与えられるディレクトリにカレント・ディレクトリを変更します。 成功すれば true を、そうでなければ nil を返します。
Changes the current directory to be the one given in str-path. If successful, true is returned; otherwise nil is returned.

(change-dir "/etc")

/etc をカレント・ディレクトリにします。
Makes /etc the current directory.



char utf8

syntax: (char str [int-index [true]])
syntax: (char int)

引数が文字列なら、引数の文字列 str から int-index 位置の文字を取り出し、その文字のアスキー・コードを返します。UTF-8 版 newLISP では Unicode 値を返します。
Given a string argument, extracts the character at int-index from str, returning either the ASCII value of that character or the Unicode value on UTF-8 enabled versions of newLISP.

int-index を省略した場合は 0 (zero) として扱われます。 int-index に続けて論理値 true を指定すると、str は多バイトの UTF-8 文字列ではなく、8ビットバイト列として扱われます。
If int-index is omitted, 0 (zero) is assumed. If int-idx is followed by a boolean true value, than the index treats str as an 8-bit byte array instead of an array of multi-byte UTF-8 characters.

空文字列では nil を返しますが、(char 0)(char nil) は、どちらも "\000" を返します。
The empty string returns nil. Both (char 0) and (char nil) will return "\000".

文字列、リスト、アレイの要素指定 を見てください。
See Indexing elements of strings and lists.

引数が整数なら、 charint 値のアスキー文字からなる文字列を返します。
Given an integer argument, char returns a string containing the ASCII character with value int.

UTF-8 版の newLISP では、int の値にUnicode を取り、UTF-8 文字が返ります。
On UTF-8–enabled versions of newLISP, the value in int is taken as Unicode and a UTF-8 character is returned.

(char "ABC")          65  ; ASCII code for "A"
(char "ABC" 1)        66  ; ASCII code for "B"
(char "ABC" -1)       67  ; ASCII code for "C"
(char "B")            66  ; ASCII code for "B"
(char "Ω")            937 ; UTF-8 code for "Ω"
(char "Ω" 1 true)     169 ; byte value at offset 1

(char 65)   "A"
(char 66)   "B"

(char (char 65))   65      ; two inverse applications

(map char (sequence 1 255))  ; returns current character set

; The Zen of UTF-8
(char (& (char "生") (char "死")))  愛 ; by @kosh_bot


chop utf8

syntax: (chop str [int-chars])
syntax: (chop list [int-elements])

第一引数が文字列に評価されたなら、chop は最後から int-char 個の文字を削除した str のコピーを返します。 引数int-char が無い時は、最後の一文字が削除されます。 chopstr を変えません。
If the first argument evaluates to a string, chop returns a copy of str with the last int-char characters omitted. If the int-char argument is absent, one character is omitted. chop does not alter str.

第一引数がリストなら、(文字列と同じように)int-elements 個が削除された list のコピーを返します。
(訳注:この場合、Common Lisp の butlast と同じ。Common Lisp の butlast は文字列に使えません。)
If the first argument evaluates to a list, a copy of list is returned with int-elements omitted (same as for strings).

(set 'str "newLISP")   "newLISP"
                      
(chop str)     "newLIS"
(chop str 2)   "newLI"
                      
str   "newLISP"

(set 'lst '(a b (c d) e))

(chop lst)     (a b (c d))
(chop lst 2)   (a b)
                      
lst   (a b (c d) e)


clean

syntax: (clean exp-predicate list)

述語 exp-predicatelist の各々の要素に適用されます。 返されるリストでは、述語が true となる全ての要素が除去されています。
(訳注:CommonLisp の remove-if と同じ。ただし、newLISP の clean は文字列に使えません。 文字列に対しては、replace で代用します。)
The predicate exp-predicate is applied to each element of list. In the returned list, all elements for which exp-predicate is true are eliminated.

clean は、述語を否定形にした filter のように動作します。
clean works like filter with a negated predicate.

(clean symbol? '(1 2 d 4 f g 5 h))    (1 2 4 5)

(filter symbol? '(1 2 d 4 f g 5 h))   (d f g h)

(define (big? x) (> x 5))         (lambda (x) (> x 5))

(clean big? '(1 10 3 6 4 5 11))   (1 3 4 5)

(clean <= '(3 4 -6 0 2 -3 0))   (3 4 2)

(clean (curry match '(a *)) '((a 10) (b 5) (a 3) (c 8) (a 9)))
  ((b 5) (c 8))

述語には、組込述語、ユーザ定義関数、ラムダ式が使えます。
The predicate may be a built-in predicate or a user-defined function or lambda expression.

他のリストの数値を使ってリストから数値を除去したい時は、(list オプションで)differenceintersect を使ってください。
(訳注:differenceintersectlist オプションで、第三引数に true を指定するということ)
For cleaning numbers from one list using numbers from another, use difference or intersect (with the list mode option).

関連する関数として、残る要素の位置を返す index や述語で true になる要素を返す filter も見てください。
See also the related function index, which returns the indices of the remaining elements, and filter, which returns all elements for which a predicate returns true.



close

syntax: (close int-file)

int-file のファイル・ハンドルで指定されたファイルを閉じます。 ハンドルは、先行する open 操作から得られます。 成功すれば closetrue を返し、そうでなければ nil を返します。
Closes the file specified by the file handle in int-file. The handle would have been obtained from a previous open operation. If successful, close returns true; otherwise nil is returned.

(close (device))   true
(close 7)          true
(close aHandle)    true

device に対して close を使うと、自動的にdevice を 0(ゼロ、スクリーン・デバイス)にリセットしますので注意してください。
Note that using close on device automatically resets it to 0 (zero, the screen device).



collect

syntax: (collect exp [int-max-count])

exp の式を評価して exp の評価が nil を返すまで、結果をリストに集めます。
Evaluates the expression in exp and collects the results in a list until evaluation of exp returns nil.

オプションとして、要素の最大数を int-max-count に指定できます。
Optionally a maximum count of elements can be specified in int-max-count.

; collect results until nil is returned
(set 'x 0)
(collect (if (<= (inc x) 10) x))  (1 2 3 4 5 6 7 8 9 10)

; collect results until nil is returned or 6 results are collected
(set 'x 0)
(collect (if (<= (inc x) 10) x) 6)  (1 2 3 4 5 6)


command-event

syntax: (command-event sym-event-handler | func-event-handler) syntax: (command-event nil)

newLISP コマンド・ラインで評価を得る前に事前処理(プリ・プロセス)するためのユーザ定義関数を指定します。 これは、インタラクティブ newLISP シェルのカスタマイズやサーバー・モードで動作している時の HTTP 要求リクエストの変更に使えます。
Specifies a user defined function for pre-processing the newLISP command-line before it gets evaluated. This can be used to write customized interactive newLISP shells and to transform HTTP requests when running in server mode.

command-event は、ユーザ定義関数のシンボルかラムダ関数のどちらかを取ります。 イベント・ハンドラ関数が文字列を返さなければ、コマンド・ラインは未翻訳のまま newLISP に渡されます。
command-event takes either a symbol of a user-defined function or a lambda function. The event-handler function must return a string or the command-line will be passed untranslated to newLISP.

強制的にプロンプトになってコマンド処理ができなくなると、関数は空文字列 "" を返します。 command-event をリセットするには、第二構文を使ってください。
To only force a prompt and disable command processing, the function should return the empty string "". To reset command-event, use the second syntax.

次の例では、コマンドが文字で始まる時、newLISP シェルは通常の Unix シェルのように動作します。 しかし、開き括弧やスペースで始まると newLISP の評価が始まります。
The following example makes the newLISP shell work like a normal Unix shell when the command starts with a letter. But starting the line with an open parenthesis or a space initiates a newLISP evaluation.

(command-event (fn (s) 
	(if (starts-with s "[a-zA-Z]" 0) (append "!" s) s)))

関連する prompt-event も見てください。 newLISP プロンプトをよりカスタマイズしたインタラクティブ・モードにできます。
See also the related prompt-event which can be used for further customizing interactive mode by modifying the newLISP prompt.

次のプログラムは、スタンド・アロンで使うことも、newLISP のスタート・アップ・ファイル init.lsp 内に入れることもできます:
The following program can be used either stand-alone or included in newLISP's init.lsp startup file:

#!/usr/local/bin/newlisp

; set the prompt to the current directory name
(prompt-event (fn (ctx) (append (real-path) "> ")))

; pre-process the command-line
(command-event (fn (s) 
    (if 
        (starts-with s "cd") 
        (string " " (true? (change-dir (last (parse s " ")))))

        (starts-with s "[a-zA-Z]" 0)
        (append "!" s)

        true s)))

コマンド・ライン翻訳関数の定義では、Unixコマンド cd が特別に扱われ、newLISP プロセスにとってもディレクトリが変更されます。 この方法なら、! でコマンド・シェルに出てから戻って来ても、newLISP はディレクトリの変更を保持します。
(訳注:単純に、コマンド・シェルに出てからディレクトリを変更しても、newLISP には反映されません。上記スクリプトのように、change-dir の実行が必要です。)
In the definition of the command-line translation function the Unix command cd gets a special treatment, to make sure that the directory is changed for newLISP process too. This way when shelling out with ! and coming back, newLISP will maintain the changed directory.

(訳注:上記例では)newLISP のコマンド入力には、最初にスペースか開き括弧が必要です。 Unix コマンドは、行の最初から入力する必要があります。
Command lines for newLISP must start either with a space or an opening parenthesis. Unix commands must start at the beginning of the line.

newLISP がオプションの -c-http を使ってサーバー・モードで走っている時は、次のような HTTP 要求リクエストを受け取ります:
When newLISP is running in server mode either using the -c or -http option, it receives HTTP requests similar to the following:

GET /index.html

あるいは、関連入り質問クエリなら:
Or if a query is involved:

GET /index.cgi?userid=joe&password=secret

command-event で指定された関数は、要求リクエストラインをフィルタまたは変形します。すなわち、全ての質問クエリにおいて、.exe で終わるファイルを使っている CGI の実行を試そうとする質問クエリを検索し、そういう要求リクエストならエラー・ページの要求リクエストに変更します:
A function specified by command-event could filter and transform these request lines, e.g.: discovering all queries trying to perform CGI using a file ending in .exe.  Such a request would be translated into a request for an error page:

;; httpd-conf.lsp
;;
;; filter and translate HTTP requests for newLISP
;; -c or -http server modes
;; reject query commands using CGI with .exe files

(command-event (fn (s)
    (let (request s)
        (when (find "?" s) ; is this a query
            (set 'request (first (parse s "?")))
            ; discover illegal extension in queries
            (when (ends-with request ".exe")
                (set 'request "GET /errorpage.html")) )
        request)
))

newlisp httpd-conf.lsp -c -d80 -w ./httpdoc でサーバー・モードを開始した時に、newLISPの方で、入力要求リクエスト質問クエリをフィルタするための command-event の定義をロードしておきます:
When starting the server mode with newlisp httpd-conf.lsp -c -d80 -w ./httpdoc newLISP will load the definition for command-event for filtering incoming requests, and the query:

GET /cmd.exe?dir

そうすれば、(訳注:上記要求リクエストは)次のように変換されます:
Would be translated into:

GET /errorpage.html

MS Windows ベースで設定の悪いウェブ・サーバーの制御を得るために、スパマーが過去において煩雑に使っていた技術を、この例は示しています。
The example shows a technique frequently used in the past by spammers on MS Windows based, bad configured web servers to gain control over servers.

httpd-conf.lsp ファイルは、インタラクティブ newLISP セッションへのファイルロードや手動の HTTP 要求リクエスト入力を簡単にデバックできます。 newLISP はコマンド・ラインを翻訳し、それを組込ウェブ・サーバーに割り当てます。 サーバー出力はシェル・ウィンドウに現れます。
httpd-conf.lsp files can easily be debugged loading the file into an interactive newLISP session and entering the HTTP requests manually. newLISP will translate the command line and dispatch it to the built-in web server. The server output will appear in the shell window.

注記:コマンド・ラインの長さは、HTTP 要求リクエスト・ヘッダの行の長さと同様に、newLISP では 512 文字に制限されます。
Note, that the command line length as well as the line length in HTTP headers is limited to 512 characters for newLISP.



cond

syntax: (cond (exp-condition-1 body-1) [(exp-condition-2 body-2) ... ])

condif のように、条件によって本体内の式を評価します。 nil や空リスト () 以外に評価される exp-condition-i が見つかるまで、exp-conditionは順番に評価されます。 それから、body-i の評価結果を cond-expression 節全体の結果として返します。 全ての条件が nil か空リストなら、cond は最後の cond-expression の値を返します。
Like if, cond conditionally evaluates the expressions within its body. The exp-conditions are evaluated in turn, until some exp-condition-i is found that evaluates to anything other than nil or an empty list (). The result of evaluating body-i is then returned as the result of the entire cond-expression. If all conditions evaluate to nil or an empty list, cond returns the value of the last cond-expression.

(define (classify x)
  (cond
    ((< x 0) "negative")
    ((< x 10) "small")
    ((< x 20) "medium")
    ((>= x 30) "big")))

(classify 15)    "medium"
(classify 22)    "nil"
(classify 100)   "big"
(classify -10)   "negative"

body-n が見つからない時は、最後の cond-expression の評価値が返されます。 もし true に評価される条件がなければ、最後の条件式の値が返ります(つまり、nil か空リスト)。
When a body-n is missing, the value of the last cond-expression evaluated is returned. If no condition evaluates to true, the value of the last conditional expression is returned (i.e., nil or an empty list).

(cond ((+ 3 4)))   7

複数の引数を持つ関数 if は、条件・本体ペアを囲む余分な括弧を必要とせずに cond のように動作します。
When used with multiple arguments, the function if behaves like cond, except it does not need extra parentheses to enclose the condition-body pair of expressions.



cons

syntax: (cons exp-1 exp-2)

exp-2 がリストとして評価されるなら、exp-1 の評価結果がリストの第一要素として挿入されて返されます。 exp-2 がリスト以外に評価された時は、exp-1 の評価結果と exp-2 がリストになって返されます。 newLISP には、ドット対 がないことに注意してください。 二つのアトムを cons することは、ドット対でないリストを作成します。
If exp-2 evaluates to a list, then a list is returned with the result of evaluating exp-1 inserted as the first element. If exp-2 evaluates to anything other than a list, the results of evaluating exp-1 and exp-2 are returned in a list. Note that there is no dotted pair in newLISP: consing two atoms constructs a list, not a dotted pair.

(cons 'a 'b)             (a b)
(cons 'a '(b c))         (a b c)
(cons (+ 3 4) (* 5 5))   (7 25)
(cons '(1 2) '(3 4))     ((1 2) 3 4)
(cons nil 1)             (nil 1)
(cons 1 nil)             (1 nil)
(cons 1)                 (1)
(cons)			 ()

newLISP の cons は、式 (cons 's nil) の結果として (s) を返す他の Lisp と違い、(s nil) を返します。 newLISP において nil は論理値で、空リストと同じではありません。 一つの newLISP セルは、一つの値のみ保持します。
Unlike other Lisps that return (s) as the result of the expression (cons 's nil), newLISP's cons returns (s nil). In newLISP, nil is a Boolean value and is not equivalent to an empty list, and a newLISP cell holds only one value.

cons は、firstrest の逆操作のように動作します(リストが一対なら、firstlast):
cons behaves like the inverse operation of first and rest (or first and last if the list is a pair):

(cons (first '(a b c)) (rest '(a b c)))   (a b c)

(cons (first '(x y)) (last '(x y)))       (x y)


constant !

syntax: (constant sym-1 exp-1 [sym-2 exp-2] ... )

機能的には set と同等です。 その上で constant は、シンボルをプロテクトし、以降の変更をできなくします。 関数 constant でセットされたシンボルは、再び constant を使うことでのみ、変更できます。 constant でプロテクトされたシンボルの内容を変更しようとすると、newLISP はエラー・メッセージを出します。 現在のコンテキストのシンボルだけに、constant を使うことができます。 これにより、ホーム・コンテキストでプロテクトされたシンボルの書き換えが防止されます。 最後の exp-n 初期値は常にオプションです。
Identical to set in functionality, constant further protects the symbols from subsequent modification. A symbol set with constant can only be modified using the constant function again. When an attempt is made to modify the contents of a symbol protected with constant, newLISP generates an error message. Only symbols from the current context can be used with constant. This prevents the overwriting of symbols that have been protected in their home context. The last exp-n initializer is always optional.

setdefinedefine-macro で初期化されたシンボルも、関数 constant を使ってプロテクトできます:
Symbols initialized with set, define, or define-macro can still be protected by using the constant function:

(constant 'aVar 123)   123
(set 'aVar 999) 
ERR: symbol is protected in function set: aVar

(define (double x) (+ x x))

(constant 'double)

;; equivalent to

(constant 'double (fn (x) (+ x x)))

一番目の例は、他の constant 宣言文によってのみ変更できる定数 aVar を定義しています。 二番目の例は、(constant 以外による)変更から double をプロテクトします。 newLISP の関数定義はラムダ関数の割り当てと等価ですから、この二ステップは最後の行の宣言文のように一つにまとめられます。 これは重量なテクニックで、一つのファイルが複数回ロードされる時のプロテクション・エラーを避けることができます。
The first example defines a constant, aVar, which can only be changed by using another constant statement. The second example protects double from being changed (except by constant). Because a function definition in newLISP is equivalent to an assignment of a lambda function, both steps can be collapsed into one, as shown in the last statement line. This could be an important technique for avoiding protection errors when a file is loaded multiple times.

割り当てる最後の値は、省略可能です。 constant は最後にセットされ、プロテクトされたシンボルの内容を返します。
The last value to be assigned can be omitted. constant returns the contents of the last symbol set and protected.

組込関数をシンボルに割り当てたり、組込関数名に他の違う関数を割り当て再定義したりすることも可能です。 関数名を変更しても、性能は変わりません。
Built-in functions can be assigned to symbols or to the names of other built-in functions, effectively redefining them as different functions. There is no performance loss when renaming functions.

(constant 'squareroot sqrt)   sqrt <406C2E>
(constant '+ add)             add <4068A6>

squarerootsqrt のように振舞います。 +(+記号)は add の混合型浮動小数点数モードを使えるように再定義されます。 結果として表示される 16 進数は組込関数のバイナリ・アドレスで、プラットフォームや OS で異なる値になります。
squareroot will behave like sqrt. The + (plus sign) is redefined to use the mixed type floating point mode of add. The hexadecimal number displayed in the result is the binary address of the built-in function and varies on different platforms and OSes.



context

syntax: (context [sym-context])
syntax: (context sym-context str | sym [exp-value])

第一構文の context は異なる名前空間のコンテキストに切り替えます。 これに続く newLISPソースの loadeval-stringsym のような関数は、新たに生成するシンボルを新たなコンテキストに置きます。
In the first syntax, context is used to switch to a different context namespace. Subsequent loads of newLISP source or functions like eval-string and sym will put newly created symbols and function definitions in the new context.

コンテキストの生成が必要な場合には、新コンテキストのシンボル名を指定すべきです。 context に渡される引数が無い時は、現コンテキストのシンボル名が返ります。
If the context still needs to be created, the symbol for the new context should be specified. When no argument is passed to context, then the symbol for the current context is returned.

コンテキストはそれ自身に評価されるので、異なるコンテキストに切り替える際、そのコンテキストが既に存在しているなら、クォートは必要ありません。
Because contexts evaluate to themselves, a quote is not necessary to switch to a different context if that context already exists.

(context 'GRAPH)          ; create / switch context GRAPH

(define (foo-draw x y z)  ; function resides in GRAPH
  (…))
                                
(set 'var 12345)
(symbols)   (foo-draw var)  ; GRAPH has now two symbols

(context MAIN)               ; switch back to MAIN (quote not required)

(print GRAPH:var)  12345    ; contents of symbol in GRAPH

(GRAPH:foo-draw 10 20 30)    ; execute function in GRAPH
(set 'GRAPH:var 6789)        ; assign to a symbol in GRAPH

コンテキストが存在する前に、そのコンテキストのシンボルが参照されると、暗黙の内にコンテキストが生成されます。
If a context symbol is referred to before the context exists, the context will be created implicitly.

(set 'person:age 0)       ; no need to create context first
(set 'person:address "")  ; useful for quickly defining data structures

コンテキストは(訳注:組込関数 new を使って)コピー可能です:
Contexts can be copied:

(new person 'JohnDoe)    JohnDoe

(set 'JohnDoe:age 99)

変数を使って、コンテキストを参照することもできます:
Contexts can be referred to by a variable:

(set 'human JohnDoe)

human:age   99

(set 'human:address "1 Main Street")

JohnDoe:address   "1 Main Street"

評価されたコンテキスト(クォート無し)を引数として与えることもできます:
An evaluated context (no quote) can be given as an argument:

> (context 'FOO)
FOO
FOO> (context MAIN)
MAIN
> (set 'old FOO)
FOO
> (context 'BAR)
BAR
BAR> (context MAIN:old)
FOO
FOO> 

同じシンボルが既に存在するなら、コンテキストとして再定義されます。
If an identifier with the same symbol already exists, it is redefined to be a context.

現コンテキスト内でのシンボルは、組込関数や niltrue のような特殊シンボルのように、それらの名前だけで参照されます。 現コンテキスト外でのシンボルは、コンテキストのシンボル名と :(コロン)を先頭に付加することで、参照できます。 異なるコンテキスト内のシンボルの引用には、コンテキスト名に '(シングル・クォート)を付加します。
Symbols within the current context are referred to simply by their names, as are built-in functions and special symbols like nil and true. Symbols outside the current context are referenced by prefixing the symbol name with the context name and a : (colon). To quote a symbol in a different context, prefix the context name with a ' (single quote).

与えられたコンテキスト内で、組込関数や MAIN のコンテキスト・シンボルと同じ名前を生成するかもしれません。 コンテキストを先付けしたシンボルは、(訳注:そのコンテキスト内で使われる)MAIN のシンボルを上書きします:
Within a given context, symbols may be created with the same name as built-in functions or context symbols in MAIN. This overwrites the symbols in MAIN when they are prefixed with a context:

(context 'CTX)
(define (CTX:new var)
    (…))
    
(context 'MAIN)

CTX:new は、MAIN の new を上書きします。 (訳注:コンテキスト CTX 内で、new は組込関数の new ではなく、上記で定義した関数 new になります。この時、コンテキスト CTX 内で組込関数 new を使うには MAIN:new とします。)
CTX:new will overwrite new in MAIN.

第二構文の context は名前空間でのシンボルを生成に使えます。 ハッシュや辞書の生成では、これを使用すべきでないことに注意してください。 ハッシュのような辞書として名前空間を使う簡単な方法については、手始めにハッシュ機能と辞書の章を見てください。
In the second syntax, context can be used to create symbols in a namespace. Note that this should not be used for creating hashes or dictionaries. For a shorter, more convenient method to use namespaces as hash-like dictionaries, see the chapter Hash functions and dictionaries.

;; create a symbol and store data in it
(context 'Ctx "abc" 123)    123
(context 'Ctx 'xyz 999)     999

;; retrieve contents from  symbol
(context 'Ctx "abc")        123
(context 'Ctx 'xyz)         999
Ctx:abc                     123
Ctx:xyz                     999

最初の三つの宣言文は、シンボルを生成して何らかのデータ型の値を格納します。 最初の宣言文は、Ctx と命名されるコンテキストも生成します。 名前としてシンボルを指定すると、その名前がシンボルから取られ、コンテキスト Ctx に同じ名前のシンボルが生成されます。
The first three statements create a symbol and store a value of any data type inside. The first statement also creates the context named Ctx. When a symbol is specified for the name, the name is taken from the symbol and creates a symbol with the same name in the context Ctx.

シンボルには、newLISPの変数名として使えるシンボルに許可されていないスペースや他の特殊文字を含めることができます。 context の第二構文は新しいシンボルのみ生成し、それに含まれる値を返します。新しい名前空間への切り替えはしません。
Symbols can contain spaces or any other special characters not typically allowed in newLISP symbols being used as variable names. This second syntax of context only creates the new symbol and returns the value contained in it. It does not switch to the new namespace.



context?

syntax: (context? exp)
syntax: (context? exp str-sym)

第一構文の context? は、exp がコンテキストに評価される時 trueを、そうでない時 nil を返す述語です。
In the first syntax, context? is a predicate that returns true only if exp evaluates to a context; otherwise, it returns nil.

(context? MAIN)   true
(set 'x 123)
(context? x)      nil

(set 'FOO:q "hola")   "hola"
(set 'ctx FOO)
(context? ctx)        true  ; ctx contains context foo

第二構文では、コンテキスト中のシンボルの存在をチェックします。 シンボルは str-sym の文字列で指定します。
The second syntax checks for the existence of a symbol in a context. The symbol is specified by its name string in str-sym.

(context? FOO "q")   true
(context? FOO "p")   nil

名前空間の変更や生成、コンテキスト中のハッシュ・シンボルの生成には、context を使ってください。
Use context to change and create namespaces and to create hash symbols in contexts.



copy

syntax: (copy exp)
syntax: (copy int-addr [bool-flag])

第一構文は評価した式をコピーを作ります。 組込関数には破壊的なものがあり、動作中に元のリストやアレイ、文字列の中身を変更します。 copy と一緒に使えば、その動作を非破壊にできます。
The first syntax makes a copy from evaluating expression in exp. Some built-in functions are destructive, changing the original contents of a list, array or string they are working on. With copy their behavior can be made non-destructive.

(set 'aList '(a b c d e f))

(replace 'c (copy aList))  (a b d e f)

aList  (a b c d e f)

(set 'str "newLISP")  "newLISP"

(rotate (copy str))  "PnewLIS"

str  "newLISP" 

関数 replacerotatecopy を使うことで、元データの変更が防がれます。 変更されたデータが返ります。
Using copy the functions replace and rotate are prevented from changing the data. A modified version of the data is returned.

bool-flagtrue にする第二構文では、メモリ・アドレスから newLISP 式をコピーします。次の二式は等価です:
The second syntax, marked by the true in bool-flag, copies a newLISP expression from a memory address.The following two expressions are equivalent:

(set 'x "hello world")
(copy x)   "hello world"
(copy (first (dump x)) true)  "hello world"

第二構文は newLISP 式を生成する C コードとのインターフェイスに役立ちます。
The second syntax can be useful when interfacing with C-code generating newLISP expressions.



copy-file

syntax: (copy-file str-from-name str-to-name)

str-from-name で与えられたパス・ファイル名のファイルを str-to-name で与えられるパス・ファイル名のファイルにコピーします。 コピーが成功すれば true が返り、失敗すれば nil が返ります。
Copies a file from a path-filename given in str-from-name to a path-filename given in str-to-name. Returns true if the copy was successful or nil, if the copy was unsuccessful.

(copy-file "/home/me/newlisp/data.lsp" "/tmp/data.lsp")


cos

syntax: (cos num-radians)

num-radians の余弦を計算し、結果を返します。
Calculates the cosine of num-radians and returns the result.

(cos 1)                      0.5403023059
(set 'pi (mul 2 (acos 0)))   3.141592654
(cos pi)                     -1


corr

syntax: (corr list-vector-X list-vector-Y)

list-vector-Xlist-vector-Y の二変数間の測定値の直線相関について、ピアソン の累積相関係数を計算します。 双方のリストは同じ長さであることが必要です。
Calculates the Pearson product-moment correlation coefficient as a measure of the linear relationship between the two variables in list-vector-X and list-vector-Y. Both lists must be of same length.

corr は次の値からなるリストです:
corr returns a list containing the following values:

namedescription
r相関係数
Correlation coefficient
b0回帰切片係数
Regression coefficient offset
b1回帰傾き係数
Regression coefficient slope
t優位検定の(訳注:スチューデントの)t 統計値
t - statistic for significance testing
df自由度
Degrees of freedom for t
p帰無仮説下での(訳注:スチューデントの)t の尾部両側の確率
Two tailed probability of t under the null hypothesis

(set 'study-time '(90 100 130 150 180 200 220 300 350 400))
(set 'test-errors '(25 28 20 20 15 12 13 10 8 6))

(corr study-time test-errors)  (-0.926 29.241 -0.064 -6.944 8 0.0001190)

帰無仮説下での尾部両側の p が約 0.0001 なので、study-timetest-errors-0.926 という負の相関係数は高い有意性があります。
The negative correlation of -0.926 between study time and test errors is highly significant with a two-tailed p of about 0.0001 under the null hypothesis.

b0 = 29.241b1 = -0.064 の回帰係数を方程式 Y = b0 + b1 * X に使えば、X (study time) の値から変数 Y (test errors) の値を推定できます。
The regression coefficients b0 = 29.241 and b1 = -0.064 can be used to estimate values of the Y variable (test errors) from values in X (study time) using the equation Y = b0 + b1 * X.



cosh

syntax: (cosh num-radians)

num-radians の双曲線余弦を計算します。 双曲線余弦は次の数式で定義されます: (exp (x) + exp (-x)) / 2num-radians が大きすぎるとオーバーフロー inf が発生します。
Calculates the hyperbolic cosine of num-radians. The hyperbolic cosine is defined mathematically as: (exp (x) + exp (-x)) / 2. An overflow to inf may occur if num-radians is too large.

(cosh 1)      1.543080635
(cosh 10)     11013.23292
(cosh 1000)   inf
(= (cosh 1) (div (add (exp 1) (exp -1)) 2))   true


count

syntax: (count list-1 list-2)

list-2 中の list-1 の要素を数え、その計数値のリストを返します。
Counts elements of list-1 in list-2 and returns a list of those counts.

(count '(1 2 3) '(3 2 1 4 2 3 1 1 2 2))   (3 4 2)
(count '(z a) '(z d z b a z y a))         (3 2)

(set 'lst (explode (read-file "myFile.txt")))
(set 'letter-counts (count (unique lst) lst))

二番目の例は、myFile.txt に出現する異なる文字を全て計数します。
The second example counts all occurrences of different letters in myFile.txt.

count の二番目のリストで計数する要素を指定する count の最初のリストは、単一であるべきです。 単一でない要素(訳注:ダブっている要素)があると、最初の存在が計数値を持ち、後の要素は 0(ゼロ)になります。
The first list in count, which specifies the items to be counted in the second list, should be unique. For items that are not unique, only the first instance will carry a count; all other instances will display 0 (zero).



cpymem 

syntax: (cpymem int-from-address int-to-address int-bytes)

int-from-address から int-bytes のメモリを int-to-address にコピーします。 この関数はメモリを直接読み書きしたり、newLISP内部(例えば、newLISP セルのタイプ・ビットや組込関数のバイナリ実行コード)をハックするために使えます。
Copies int-bytes of memory from int-from-address to int-to-address. This function can be used for direct memory writing/reading or for hacking newLISP internals (e.g., type bits in newLISP cells, or building functions with binary executable code on the fly).

この関数は newLISP 内部をよく熟知した上で使うよう注意してください。 cpymem を誤って使うと、システムがクラッシュしたり、不安定になったりします。
Note that this function should only be used when familiar with newLISP internals. cpymem can crash the system or make it unstable if used incorrectly.

(set 's "0123456789")

(cpymem "xxx" (+ (address s) 5) 3)

s   "01234xxx89")

この例では、文字列変数に直接文字列をコピーしています。
The example copies a string directly into a string variable.

次の例は、一からバイナリ・コードの新しい関数を作成し、その部品を走らせ、二つの数を足し算します。 示してあるアセンブリ言語の小品は、二つの数を足し算して結果を返す X86 (Intel CPU) コードです:
he following example creates a new function from scratch, runs a piece of binary code, and adds up two numbers. This assembly language snippet shows the x86 (Intel CPU) code to add up two numbers and return the result:

 55       push ebp
 8B EC    mov  ebp, esp
 8B 45 08 mov  eax, [ebp+08]
 03 45 0C add  eax, [ebp+0c]
 5D       pop  ebp
 C3       ret

 ; for Win32/stdcall change last line
 C2 08 00 ret 

このバイナリ表現を newLISP で作成した新関数に貼り付けます:
The binary representation is attached to a new function created in newLISP:

; set up 32-bit version of machine code
; on Windows use 32-bit version of newLISP
(set 'foo-code (append
     (pack "bbbbbbbbbb" 0x55 0x8B 0xEC 0x8B 0x45 0x08 0x03 0x45 0x0C 0x5D)
     (if (= ostype "Windows") (pack "bbb" 0xC2 0x08 0x00) (pack "b" 0xC3))))

; put a function cell template into foo, protect symbol from deletion
(constant 'foo print)

; put the correct type, either 'stdcall' or 'cdecl'
(cpymem (pack "ld" (if (= ostype "Windows") 8456 4360)) (first (dump foo)) 4)

; put the address of foo-code into the new function cell
(cpymem (pack "ld" (address foo-code)) (+ (first (dump foo)) 12) 4)

; take the name address from the foo symbol, copy into function cell
(set 'sym-name (first (unpack "lu" (+ (address 'foo) 8))))
(cpymem (pack "ld" sym-name) (+ (first (dump foo)) 8) 4)

; test the new function
(println "3 * 4 -> " (foo 3 4))

この例は、全てのハードウェア・プラットフォームや OS で動作するものではありません。
The last example will not work on all hardware platforms and OSs.

newLISP セルからバイナリ・アドレスとその内容を取り出すのには、関数 dump を使ってください。
Use the dump function to retrieve binary addresses and the contents from newLISP cells.



crc32

syntax: (crc32 str-data)

str-data のバッファから、初期値が 0xffffffff で始まる 32 ビット CRC(巡回冗長検査)値を計算します。 crc32 計算には www.w3.org で公開されているアルゴリズムを使っています。
Calculates a running 32-bit CRC (Circular Redundancy Check) sum from the buffer in str-data, starting with a CRC of 0xffffffff for the first byte. crc32 uses an algorithm published by www.w3.org.

(crc32 "abcdefghijklmnopqrstuvwxyz")   1277644989

安全でないデータ伝送において確実なベリファイを実施するために、crc32 がよく使われます。
crc32 is often used to verify data integrity in unsafe data transmissions.



crit-chi2

syntax: (crit-chi2 num-probability int-df)

統計的帰無仮説の有意を検定するために、 帰無仮説下で与えられた危険率(訳注:有意水準ともいう)num-probability と自由度 int-df  により、最小限界のカイ2乗値 を計算します。(訳注:EXCEL の CHIINV(確率, 自由度)に相当。カイ二乗分布カイ二乗検定 も参考になります)
Calculates the critical minimum Chi²  for a given confidence probability num-probability under the null hypothesis and the degrees of freedom in int-df  for testing the significance of a statistical null hypothesis.

10.2.0 以前のバージョンでは、(訳注:引数として)確率 p のかわりに (1.0 - p) (訳注:信頼率)を取っていたことを記しておきます。
Note that versions prior to 10.2.0 took (1.0 - p) for the probability instead of p.

(crit-chi2 0.01 4)   13.27670443

逆関数 prob-chi2 も見てください。
See also the inverse function prob-chi2.



crit-f

syntax: (crit-f num-probability int-df1 int-df2)

F 検定 を用いて統計的帰無仮説の有意を検定するために、帰無仮説下で与えられた危険率(訳注:有意水準ともいう)num-probability と自由度 int-df1int-df2 により、最小限界の 値を計算します。(訳注:EXCEL の FINV(確率, 自由度1, 自由度2)に相当。F分布も参考になります)
Calculates the critical minimum for a given confidence probability num-probability under the null hypothesis and the degrees of freedom given in int-df1 and int-df2 for testing the significance of a statistical null hypothesis using the F-test.

(crit-f 0.05 10 12)   2.753386727

逆関数の prob-f も見てください。
See also the inverse function prob-f.



crit-t

syntax: (crit-t num-probability int-df)

統計的帰無仮説の有意を検定するために、帰無仮説下で与えられた危険率(訳注:有意水準ともいう)num-probability と自由度 int-df により、最小限界のスチューデントの t を計算します。(訳注:EXCEL の CHIINV( 2 * 確率, 自由度)に相当。t 分布t 検定も参考になります)
Calculates the critical minimum Student's t for a given confidence probability num-probability under the null hypothesis and the degrees of freedom in int-df  for testing the significance of a statistical null hypothesis.

(crit-t 0.05 14)   1.761310142

逆関数の prob-t も見てください。
See also the inverse function prob-t.



crit-z

syntax: (crit-z num-probability)

統計的有意と信頼区間を検定するために、正規分布において与えられた累積確率 num-probability の最小となる Z 値を計算します。(訳注:EXCELのNORMSINV(確率)に相当。)
Calculates the critical normal distributed Z value of a given cumulated probability num-probability for testing of statistical significance and confidence intervals.

(crit-z 0.999)   3.090232372

逆関数 prob-z も見てください。
See also the inverse function prob-z.



current-line

syntax: (current-line)

read-line 操作の最後の内容を取り出します。 current-line の内容は、write-line を文字列パラメータ無しで使う場合にも暗黙的に使われます。
Retrieves the contents of the last read-line operation. current-line's contents are also implicitly used when write-line is called without a string parameter.

次に示すソースは、Unix コマンド・ラインのフィルタを作る時の典型的なコード・パターンです:
The following source shows the typical code pattern for creating a Unix command-line filter:

#!/usr/local/bin/newlisp
 
(set 'inFile (open (main-args 2) "read"))
(while (read-line inFile) 
  (if (starts-with (current-line) ";;")
    (write-line)))
(exit)

プログラムは次のようにして起動します:
The program is invoked:

./filter myfile.lsp

filter スクリプトを実行すると、コマンド・ライン引数で与えられたファイルから、;; で始まるコメント行が全て表示されます。
This displays all comment lines starting with ;; from a file given as a command-line argument when invoking the script filter.



curry

syntax: (curry func exp)

func に与えられた二つの引数をとる関数f(x, y) を、一つの引数をとる関数fx(y) に変換します。 curry は、引数を評価しないマクロのように作用します。 その代わり、func の適用時に評価されます。(訳注:名前の由来は、カレー化でどうぞ)
Transforms func from a function f(x, y) that takes two arguments into a function fx(y) that takes a single argument. curry works like a macro in that it does not evaluate its arguments. Instead, they are evaluated during the application of func.

(set 'f (curry + 10))   (lambda ($x) (+ 10 $x))

(f 7)   17

(filter (curry match '(a *)) '((a 10) (b 5) (a 3) (c 8) (a 9)))
  ((a 10) (a 3) (a 9))

(clean (curry match '(a *)) '((a 10) (b 5) (a 3) (c 8) (a 9)))
  ((b 5) (c 8))

(map (curry list 'x) (sequence 1 5))
  ((x 1) (x 2) (x 3) (x 4) (x 5))

curry は全ての二変数関数に使えます。
curry can be used on all functions taking two arguments.



date utf8

syntax: (date)
syntax: (date int-secs [int-offset])
syntax: (date int-secs int-offset str-format)

第一構文はローカル・タイム・ゾーンの現在の日付と時刻を文字列表現で返します。 int-secs が範囲外なら nil を返します。
The first syntax returns the local time zone's current date and time as a string representation. If int-secs is out of range, nil is returned.

第二構文の dateint-secs の秒数をローカル・タイム・ゾーンの日付/時刻の文字列表現に変換します。 int-secs の数値は、通常 date-value を使ってシステムから取り出します。 オプションとして、タイム・ゾーンのオフセットを(分単位で) int-offset に指定できます。 int-offset は文字列に変換する前の int-sec から加算もしくは減算されます。 範囲外の int-secs または 無効な str-format が指定されると、空文字列 "" を返します。
In the second syntax, date translates the number of seconds in int-secs into its date/time string representation for the local time zone. The number in int-secs is usually retrieved from the system using date-value. Optionally, a time-zone offset (in minutes) can be specified in int-offset, which is added or subtracted before conversion of int-sec to a string. If int-secs is out of range or an invalid str-format is specified, an empty string "" is returned.

(date)                    "Fri Oct 29 09:56:58 2004"

(date (date-value))       "Sat May 20 11:37:15 2006" 
(date (date-value) 300)   "Sat May 20 16:37:19 2006"  ; 5 hours offset
(date 0)                  "Wed Dec 31 16:00:00 1969"
(date 0 (now 0 -2))       "Thu Jan  1 00:00:00 1970"  ; Unix epoch

日付と時刻の文字列による表示は基になっているオペレーティングシステムによります。
The way the date and time are presented in a string depends on the underlying operating system.

二番目の例はグリニッジ・タイム・ゾーンで 1-1-1970 0:0 を示していますが、パシフィック・スタンダード・タイム (PST) の時、8時間前を表示します。 date は与えられた int-secs が協定世界時(UTC、以前はグリニッジ標準時(GMT))だと仮定して、ローカル・タイム・ゾーンによる時刻に変換します。
(訳注:協定世界時、UTC - Universal Time, Coordinated)
The second example would show 1-1-1970 0:0 when in the Greenwich time zone, but it displays a time lag of 8 hours when in Pacific Standard Time (PST). date assumes the int-secs given are in Coordinated Universal Time (UTC; formerly Greenwich Mean Time (GMT)) and converts it according to the local time-zone.

三番目の構文は、str-format で指定されたフォーマットを使ってフル・カスタムな日付文字列を作ります。 これにより、日や月の名前をその土地柄に合わせた形へ変更できます:
The third syntax makes the date string fully customizable by using a format specified in str-format. This allows the day and month names to be translated into results appropriate for the current locale:

(set-locale "de_DE")  ("de_DE" ",")      

; on Linux - no leading 0 on day with %-d
(date (date-value) 0 "%A %-d. %B %Y")   "Montag  7. März 2005" 

(set-locale "C")  ; default POSIX

(date (date-value) 0 "%A %B %d %Y")     "Monday March 07 2005"

; suppressing leading 0 on MS Windows using #
(date (date-value) 0 "%a %#d %b %Y")    "Mon 7 Mar 2005" 

(set-locale "de_DE") ; on macOS

(date (date-value) 0 "%x")  "07.03.2005"   ; day month year

(set-locale "C")

(date (date-value) 0 "%x")  "03/07/05"     ; month day year

次の表は、 MS Windows と Linux/Unix の両プラットフォームで利用可能な全てのフォーマット指定子の要約です。 Linux/Unix では、さらに多くのフォーマット・オプションが利用可能です。 詳細は、個々のプラットフォームの Cライブラリにある C関数 strftime() のマニュアル・ページを調べてください。
The following table summarizes all format specifiers available on both MS Windows and Linux/Unix platforms. More format options are available on Linux/Unix. For details, consult the manual page for the C function strftime() of the individual platform's C library.

formatdescription
%a現ロケールでの省略した曜日
abbreviated weekday name according to the current locale
%A現ロケールでの完全な曜日
full weekday name according to the current locale
%b現ロケールでの省略した月の呼び名
abbreviated month name according to the current locale
%B現ロケールでの完全な月の呼び名
full month name according to the current locale
%c現ロケールで好まれる日付と時刻の表現
preferred date and time representation for the current locale
%dその月の日にち(範囲 01–31)
day of the month as a decimal number (range 01–31)
%H24時間制で使われる時間(範囲 00-23)
hour as a decimal number using a 24-hour clock (range 00–23)
%I12時間制で使われる時間(範囲 00-11)
hour as a decimal number using a 12-hour clock (range 01–12)
%j年間通しての日数(範囲 001-366)
day of the year as a decimal number (range 001–366)
%m月数(範囲 01-12)
month as a decimal number (range 01–12)
%M分数
minute as a decimal number
%p与えられた時間よって 'am' か 'pm' のどちらか、現ロケールに対応する文字列
either 'am' or 'pm' according to the given time value or the corresponding strings for the current locale
%S0-61 の秒数(60 と 閏秒を考慮した 61 )
second as a decimal number 0–61 (60 and 61 to account for occasional leap seconds)
%U週の最初を日曜日とする今年の週数
week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week
%w日曜を 0 とする曜日数
day of the week as a decimal, Sunday being 0
%W週の最初を月曜日とする今年の週数
week number of the current year as a decimal number, starting with the first Monday as the first day of the first week
%x現ロケールで好まれる時刻無しの日付表現
preferred date representation for the current locale without the time
%X現ロケールで好まれる日付無しの時刻表現
preferred time representation for the current locale without the date
%y世紀を含まない年数(範囲 00-99)
year as a decimal number without a century (range 00–99)
%Y世紀を含む年数
year as a decimal number including the century
%zタイム・ゾーンの名前か省略形(MS Windows では %Z と同じ、Unix では異なる)
time zone or name or abbreviation (same as %Z on MS Windows, different on Unix)
%Zタイム・ゾーンの名前か省略形(MS Windows では %z と同じ、Unix では異なる)
time zone or name or abbreviation (same as %z on MS Windows, different on Unix)
%%文字 '%'
a literal '%' character

日付の表示の先頭のゼロは、Linux や FreeBSD では "%-d" を使って、 OpenBSD や SunOS/Solaris や macOS では "%e" を使って、省けます。MS Windowsでは "%#d" を使います。
Leading zeroes in the display of decimal day numbers can be suppressed using "%-d" on Linux and FreeBSD and using "%e" on OpenBSD, SunOS/Solaris and macOS. On MS Windows use "%#d".

date-valuedate-listdate-parsetime-of-daytimenow も見てください。
See also date-value, date-list, date-parse, time-of-day, time, and now.



date-list

syntax: (date-list int-seconds [int-index])
syntax: (date-list)

与えられた 1970年1月1日 00:00:00 からの秒数による 年、月、日、時、分、秒、年の始めからの日数、週の始めからの日数のリストを返します。 日付と時刻は UTC で与えられるので、ローカルのタイムゾーンとは違うかもしれません。
Returns a list of year, month, date, hours, minutes, seconds, day of year and day of week from a time value given in seconds after January 1st, 1970 00:00:00. The date and time values aren given as UTC, which may differ from the local timezone.

パラメータなしの date-list は、(date-value) の戻り値である現在時間の秒数からリストを生成します。
When no parameters are given date-list generates the list from the number of seconds for the current time, return of (date-value).

週の始めからの日数は、月曜日から日曜日に対して 1 から 7 の範囲です。
The week-day value ranges from 1 to 7 for Monday thru Sunday.

(date-list 1282479244)       (2010 8 22 12 14 4 234 7)
(date-list 1282479244 0)     2010 ; year
(date-list 1282479244 -2)    234  ; day of year

(date-value (date-list 1282479244))  1282479244

(date-list 0)    (1970 1 1 0 0 0 1 4) ; Thursday 1st, Jan 1970

リストから特定の数値を返させるために、第2オプション・パラメータ int-index が使えます。
A second optional int-index parameter can be used to return a specific member of the list.

date-list は、date-value の逆操作です。
date-list is the inverse operation of date-value.



date-parse

syntax: (date-parse str-date str-format)

date で見つかるのと同じフォーマット規則を使った str-format で定義されたフォーマットを使って、テキスト文字列 str-date の日付を解析します。 関数 date-parse は、UTC 1970年1月1日 を 0 として経過した UTC 秒数を 2038年1月19日の 2147472000 まで返します。
Parses a date from a text string in str-date using a format as defined in str-format, which uses the same formatting rules found in date. The function date-parse returns the number of UTC seconds passed since January 1st, 1970 UTC starting with 0 and up to 2147472000 for a date of January 19th, 2038.

この関数は MS Windows プラットフォームでは利用できません(訳注:Windows 用には拙作 date-parse があります)。 以前のバージョンでは、parse-date と呼ばれていました。この古い名称は推奨しません。
This function is not available on MS Windows platforms. The function was named parse-date in previous versions. The old form is deprecated.

(date-parse "2007.1.3" "%Y.%m.%d")     1167782400
(date-parse "January 10, 07" "%B %d, %y")     1168387200

; output of date-parse as input value to date-list produces the same date 

(date-list (date-parse "2010.10.18 7:00" "%Y.%m.%d %H:%M"))
 (2010 10 18 7 0 0 290 1)

利用できる全てのフォーマット記述子デスクリプタは、関数 date で見てください。
See the date function for all possible format descriptors.



date-value

syntax: (date-value int-year int-month int-day [int-hour int-min int-sec])
syntax: (date-value list-date-time)
syntax: (date-value)

第一構文の date-value は、1970-1-1 00:00:00 から与えられた日付と時刻までの秒数を返します。 時、分、秒のパラメータはオプションです。 時間は協定標準時(UTC)を想定し、現タイム・ゾーンには合わせてはいません。
In the first syntax, date-value returns the time in seconds since 1970-1-1 00:00:00 for a given date and time. The parameters for the hour, minutes and seconds are optional. The time is assumed to be Coordinated Universal Time (UTC), not adjusted for the current time zone.

第二構文では、同じデータをリストで与えることができます。 第一構文と同様、時、分、秒はオプションです。
In the second syntax the same data can be given in a list. As with the first syntax, numbers for the hour, minutes and seconds are optional.

第二構文の date-value は(訳注:1970-1-1 00:00:00 から)現時刻までの秒数を返します。
In the second syntax, date-value returns the time value in seconds for the current time.

(date-value 2002 2 28)        1014854400
(date-value '(2002 2 28))     1014854400
(date-value 1970 1 1 0 0 0)   0
                                 
(date (date-value (now)))     "Wed May 24 10:02:47 2006" 
(date (date-value))           "Wed May 24 10:02:47 2006"
(date)                        "Wed May 24 10:02:47 2006"

関数date-listdate-value をリストに戻すために使えます:
The function date-list can be used to transform a date-value back into a list:

(date-list 1014854400)   (2002 2 28 0 0 0)
(date-value (date-list 1014854400))   1014854400

datedate-listdate-parsetime-of-daytimenow も見てください。
See also date, date-list, date-parse, time-of-day, time, and now.



debug

syntax: (debug func)

trace を呼び出してユーザ定義関数 func の評価を始めます。 debug は、(trace true) を実行してデバック・モードで関数に入るためのショート・カットです。
Calls trace and begins evaluating the user-defined function in func. debug is a shortcut for executing (trace true), then entering the function to be debugged.

;; instead of doing
(trace true)
(my-func a b c)
(trace nil)

;; use debug as a shortcut
(debug (my-func a b c))

debug あるいは trace モード中に、エラー・メッセージが出力されることがあります。例外を起こした関数が 0nil を返して、プロセスを続けます。このようにデバック中は、変数とプログラムの現在の状態が監視されたままになります。
When in debug or trace mode, error messages will be printed. The function causing the exception will return either 0 or nil and processing will continue. This way, variables and the current state of the program can still be inspected while debugging.

関数trace も見てください。
See also the trace function.



dec !

syntax: (dec place [num])

place の数値から 1.0 か、オプション数値の num を減じて返します。 dec は浮動小数点演算を実行し、整数は浮動小数点型に変換されます。
The number in place is decremented by 1.0 or the optional number num and returned. dec performs float arithmetic and converts integer numbers passed into floating point type.

place はシンボル、リスト構造内の位置、式によって返される数値のいずれかです。
place is either a symbol or a place in a list structure holding a number, or a number returned by an expression.

(set x 10)     10
(dec x)        9
x              9
(dec x 0.25)   8.75
x              8.75

place のシンボルが nil なら、0.0 として扱われます:
If the symbol for place contains nil, it is treated as if containing 0.0:

z              nil
(dec z)        -1

(set z nil)
(dec z 0.01)   -0.01

リスト構造内の位置や他の式の戻り値も更新されます:
Places in a list structure or a number returned by another expression can be updated too:

(set 'l '(1 2 3 4))

(dec (l 3) 0.1)  3.9

(dec (first l))  0

l  (0 2 3 3.9)

(dec (+ 3 4))  6

整数モードの減算には、関数 -- を使ってください。 浮動小数点モードの加算には、関数 inc を使ってください。
Use the -- function to decrement in integer mode. Use the inc function to increment numbers floating point mode.



def-new

syntax: (def-new sym-source [sym-target])

この関数は、new のように動作しますが、sym-source のシンボルからそのコンテキストとシンボル一個のみコピーします。 sym-target が無い時は、同じ名前のシンボルが現コンテキストに作られます。 sym-source 内で参照可能な全てのシンボルが現コンテキストで参照可能なシンボルとして移植されますが、そのコンテキストは MAIN 以外でなければなりません。(訳注:sym-target 無しをコンテキスト MAIN で使うとエラーになります。)
This function works similarly to new, but it only creates a copy of one symbol and its contents from the symbol in sym-source. When sym-target is not given, a symbol with the same name is created in the current context. All symbols referenced inside sym-source will be translated into symbol references into the current context, which must not be MAIN.

引数に sym-target があれば、em>sym-target のシンボルで参照できるシンボルとコンテキストのコピーが作られます。 名前の変更だけでなく、異なるコンテキストへの配置も可能です。 sym-source 内で参照できる全てシンボルが、目標コンテキストの参照シンボルとして移植されます。
If an argument is present in sym-target, the copy will be made into a symbol and context as referenced by the symbol in sym-target. In addition to allowing renaming of the function while copying, this also enables the copy to be placed in a different context. All symbol references in sym-source with the same context as sym-source will be translated into symbol references of the target context.

def-new は生成したシンボルを返します:
def-new returns the symbol created:

> (set 'foo:var '(foo:x foo:y))
(foo:x foo:y)

> (def-new 'foo:var 'ct:myvar)
ct:myvar

> ct:myvar
(ct:x ct:y)

> (context 'K)

K> (def-new 'foo:var)
var

K> var
(x y)

次の例は静的スコープ関数(訳注:デフォルト・ファンクタ)をその名前空間自身に作る方法を示しています:
The following example shows how a statically scoped function can be created by moving it its own namespace:

> (set 'temp (lambda (x) (+ x x)))
(lambda (x) (+ x x))
> (def-new 'temp 'double:double)
double:double
> (double 10)
20
> double:double
(lambda (double:x) (+ double:x double:x))

次で定義する def-static は、レキシカルに保護される名前空間に置かれる関数(訳注:デフォルト・ファンクタ)を作るために利用できます:
The following definition of def-static can be used to create functions living in their own lexically protected name-space:

(define (def-static s body) 
      (def-new 'body (sym s s)))

(def-static 'acc (lambda (x)
          (inc sum x)))

> (acc 1)
1
> (acc 1)
2
> (acc 8)
10
>

関数 def-new は、コンテキストを完全にコピーする new よりも簡単な方法で、コンテキストやコンテキスト・オブジェクトを構成するために使えます。
The function def-new can be used to configure contexts or context objects in a more granular fashion than is possible with new, which copies a whole context.



default

syntax: (default context)

context のデフォルト・ファンクタの中身を返します。
Return the contents of the default functor in context.

(define Foo:Foo 123)

(default Foo)  123

(setf (default Foo) 456)
(set 'ctx Foo)

(default ctx)  456
Foo:Foo        456

多くの場合、newLISP はコンテキスト名を見ると、自動的にデフォルト・ファンクタにします。 そうならない場合に、関数 default を利用できます。
In many situations newLISP defaults automatically to the default functor when seeing a context name. In circumstances where this is not the case, the default function can be used.



define !

syntax: (define (sym-name [sym-param-1 ... ]) [body-1 ... ])
syntax: (define (sym-name [(sym-param-1 exp-default) ... ]) [body-1 ... ])
syntax: (define sym-name exp)

sym-param-1 以下のオプション・パラメータを持つ新しい関数 sym-name を定義します。 define はラムダ式を sym-name に割り当てるのと等価です。 定義された関数が呼び出されると、引数全てが評価されて sym-param-1 以下の変数に割り当てられ、body-1 以下の式群が評価されます。 関数が定義されると、sym-name に束縛されたラムダ式が返ります。
Defines the new function sym-name, with optional parameters sym-param-1—. define is equivalent to assigning a lambda expression to sym-name. When calling a defined function, all arguments are evaluated and assigned to the variables in sym-param-1—, then the body-1— expressions are evaluated. When a function is defined, the lambda expression bound to sym-name is returned.

全ての定義パラメータはオプションです。 ユーザ定義関数が引数無しで呼ばれると、パラメータには nil が入ります。 もし、パラメータが exp-default で指定されるデフォルト値を持っている場合は、その値をとります。
All parameters defined are optional. When a user-defined function is called without arguments, those parameters assume the value nil. If those parameters have a default value specified in exp-default, they assume that value.

define の戻り値は、割り当てられたラムダ式です。 ユーザ定義関数が呼ばれた時の戻り値は、関数本体で最後に評価された式です。
The return value of define is the assigned lambda expression. When calling a user-defined function, the return value is the last expression evaluated in the function body.

(define (area x y) (* x y))   (lambda (x y) (* x y))
(area 2 3)                    6

define を使わず、area を関数に定義することも可能です。
As an alternative, area could be defined as a function without using define.

(set 'area (lambda (x y) (* x y))

lambdafn 式は、シンボルに定義されることなくそれ自身で匿名関数として使われることもあります:
lambda or fn expressions may be used by themselves as anonymous functions without being defined as a symbol:

((lambda ( x y) (* x y)) 2 3)   6
((fn ( x y) (* x y)) 2 3)       6

fnlambda 記述の短縮形です。
fn is just a shorter form of writing lambda.

パラメータには、デフォルト値を指定できます:
Parameters can have default values specified:

(define (foo (a 1) (b 2))
  (list a b))
    
(foo)       (1 2)
(foo 3)     (3 2)
(foo 3 4)   (3 4)

exp-default の式は、関数の呼ばれた環境で評価されます。
Expressions in exp-default are evaluated in the function's current environment.

(define (foo (a 10) (b (div a 2))) 
  (list a b))

(foo)       (10 5)
(foo 30)    (30 15)
(foo 3 4)   (3 4)

第二形式の define は、関数 set のように動作します。
The second version of define works like the set function.

(define x 123)     123
;; is equivalent to
(set 'x 123)       123

(define area (lambda ( x y) (* x y)))
;; is equivalent to
(set 'area (lambda ( x y) (* x y)))
;; is equivalent to
(define (area x y) (* x y))

プロテクトされたシンボルを再定義すると、エラー・メッセージが発生します。
Trying to redefine a protected symbol will cause an error message.



define-macro

syntax: (define-macro (sym-name [sym-param-1 ... ]) body)
syntax: (define-macro (sym-name [(sym-param-1 exp-default) ... ]) body)

define-macro を使って定義された関数は、他のLISPのように変数を展開しない fexpr と呼ばれます(訳注: fexpr とは、オペランドが評価されずに渡される関数)。 newLISP では、今まで通りマクロと呼んでいます。 というのも、標準的でない引数の評価形式を持つ特殊な構文形態を作るという同じ目的で書かれるからです。 define-macro を使って作られた関数は、expandletex を使ったテンプレート展開式と結合できます。
Functions defined using define-macro are called fexpr in other LISPs as they don't do variable expansion. In newLISP they are still called macros, because they are written with the same purpose of creating special syntax forms with non-standard evaluation patterns of arguments. Functions created using define-macro can be combined with template expansion using expand or letex.

v.10.5.8 から newLISP には macro を使った拡張マクロもあります。
Since v.10.5.8, newLISP also has expansion macros using macro.

sym-param-1 以下をオプション引数として、新しい fexpr の sym-name を定義します。 define-macro は、ラムダ・マクロ式をシンボルに割り当てるのと等価です。 関数 define-macro が呼ばれると、評価されない引数が変数 sym-param-1 ... に割り当てられます。 その後、body の式群が評価されます。 関数define-macro が評価されると、ラムダ・マクロ式が返ります。
Defines the new fexpr sym-name, with optional arguments sym-param-1. define-macro is equivalent to assigning a lambda-macro expression to a symbol. When a define-macro function is called, unevaluated arguments are assigned to the variables in sym-param-1 .... Then the body expressions are evaluated. When evaluating the define-macro function, the lambda-macro expression is returned.

(define-macro (my-setq p1 p2) (set p1 (eval p2))) 
 (lambda-macro (p1 p2) (set p1 (eval p2)))

(my-setq x 123)   123
x                 123

特定の引数の評価を先延ばしする組込関数のような新しい関数を作成できます。 fexprs はパラメーター・リスト内部の引数にもアクセスでき、すでに newLISP に組み込まれているようなフロー制御関数の作成に使えます。
New functions can be created to behave like built-in functions that delay the evaluation of certain arguments. Because fexprs can access the arguments inside a parameter list, they can be used to create flow-control functions like those already built-in to newLISP.

定義された引数は、全てオプションです。 マクロが引数無しで呼ばれると、パラメータには nil が入ります。 パラメータが exp-default で指定されるデフォルト値を持つ場合は、それらが入ります。
All parameters defined are optional. When a macro is called without arguments, those parameters assume the value nil. If those parameters have a default value specified in exp-default, they assume that default value.

(define-macro (foo (a 1) (b 2))
  (list a b))
    
(foo)       (1 2)
(foo 3)     (3 2)
(foo 3 4)   (3 4)

exp-default の式は、関数が呼ばれた環境で評価されます。
Expressions in exp-default are evaluated in the function's current environment.

(define-macro (foo (a 10) (b (div a 2))) 
  (list a b))

(foo)       (10 5)
(foo 30)    (30 15)
(foo 3 4)   (3 4)

fexpr には注記すべき危険性が存在します。define-macro の定義で使っているのと同じ変数名がパラメータとして渡されることです。 このような場合(訳注:下記の例)、fexpr の内部変数は意図した値と違って nil を受け取ってしまいます:
Note that in fexprs, the danger exists of passing a parameter with the same variable name as used in the define-macro definition. In this case, the fexpr's internal variable would end up receiving nil instead of the intended value:

;; not a good definition!

(define-macro (my-setq x y) (set x (eval y)))  

;; symbol name clash for x

(my-setq x 123)   123
x                 nil

変数捕捉 として知られるこの問題を避けて、安全な define-macro を書く方法は、いくつかあります:
There are several methods that can be used to avoid this problem, known as variable capture, by writing hygienic define-macros:

;; a define-macro as a lexically isolated function
;; avoiding variable capture in passed parameters

(context 'my-setq)

(define-macro (my-setq:my-setq x y) (set x (eval y)))  

(context MAIN)

(my-setq x 123)   123  ; no symbol clash
x                 123

例題の定義では、レキシカルに隔離されていて変数捕捉が起こりません。 (my-setq:my-setq …) を使って関数を呼び出す代わりに、(my-setq …) だけで呼び出せます。 それは、デフォルト・ファンクション だからです。
The definition in the example is lexically isolated, and no variable capture can occur. Instead of the function being called using (my-setq:my-setq …), it can be called with just (my-setq …) because it is a default function.

第2の可能性は、args を使って渡されるパラメータに参照することです:
The second possibility is to refer to passed parameters using args:

;; avoid variable capture in macros using the args function

(define-macro (my-setq) (set (args 0) (eval (args 1))))

変数補足に耐性のある拡張関数 macro も見てください。
See also the macro expansion function not susceptible to variable capture.



delete 

syntax: (delete symbol [bool])
syntax: (delete sym-context [bool])

symbol のシンボルや sym-context のコンテキストと、それに含まれる全てのシンボルを newLISP シンボル・テーブルから削除します。 シンボルの参照値は nil に変わります。 Deletes a symbol symbol, or a context in sym-context with all contained symbols from newLISP's symbol table. References to the symbol will be changed to nil.

第一構文では symbol のシンボルを削除します。 そのため、他の式でそのシンボルを参照しても、nil に変わっているでしょう。
In the first syntax deletes a symbol symbol and references to the symbol in other expressions will be changed to nil.

第二構文では sym-context で参照される名前空間の全シンボルを削除します。 そのため、他の式でそれらを参照しても、nil に変わっているでしょう。 sym-context のコンテキスト・シンボルは通常のシンボルに変わり、nilが入ります。
In the second syntax all symbols of the namespace referred to by sym-context will be deleted and references to them in other espressions will be changed to nil. The context symbol sym-context will be changed to a normal symbol containing nil.

bool の式が true に評価されると、シンボルが参照されていない時のみ、削除されます。
When the expression in bool evaluates to true, symbols are only deleted when they are not referenced.

bool の式が nil に評価されると、シンボルは参照がチェックされずに削除されます。 名前空間の外でシンボルの存在を参照していない時のみ、このモードを使用すべきだということに、注意してください。 もし、外部参照があるのにこのモードを使えば、外部参照が nil にセットされず、システム・クラッシュを導きかねません。 ハッシュの名前空間の削除や変数が厳密に非公開として扱われるオブジェクト・システムの名前空間の削除に、このモードを使えます。
When the expression in bool evaluates to nil, symbols will be deleted without any reference checking. Note that this mode should only be used, if no references to the symbol exist outside it's namespace. If external references exist, this mode can lead to system crashes, as the external reference is not set to nil when using this mode. This mode can be used to delete namespace hashes and to delete namespaces in object systems, where variables are strictly treated as private.

組込関数のようなプロテクトされたシンボルとか、niltrue のような特殊シンボルは削除できません。
Protected symbols of built-in functions and special symbols like nil and true cannot be deleted.

シンボルの削除に成功すると、deletetrue を返し、 失敗すると nil を返します。
delete returns true if the symbol was deleted successfully or nil if the symbol was not deleted.

コンテキスト・シンボルを削除する時、最初の delete はコンテキスト名前空間の中身を削除して、コンテキスト・シンボルを通常の単一変数シンボルに落とします。二回目の delete はシンボル・テーブルからシンボルを削除します。
When deleting a context symbol, the first delete removes the context namespace contents and demotes the context symbol to a normal mono-variable symbol. A second delete will remove the symbol from the symbol table.

(set 'lst '(a b aVar c d))

(delete 'aVar)  ; aVar deleted, references marked nil

lst   (a b nil c d)

(set 'lst '(a b aVar c d))

(delete 'aVar true)  
 nil ; protect aVar if referenced

lst   (a b aVar c d)

;; delete all symbols in a context
(set 'foo:x 123)
(set 'foo:y "hello")

(delete 'foo)   foo:x, foo:y deleted

最後の例では、コンテキスト foo 内のシンボルのみが削除されますが、コンテキスト・シンボル foo 自身は削除されません。 foo は通常のプロテクトされていないシンボルになり、nil が入ります。
In the last example only the symbols inside context foo will be deleted but not the context symbol foo itself. It will be converted to a normal unprotected symbol and contain nil.

実行中の関数の一部になっている式を削除すると、システムをクラッシュしたり、予期せぬ影響をもたらすことがあることに注意してください。
Note that deleting a symbol that is part of an expression which is currently executing can crash the system or have other unforeseen effects.



delete-file

syntax: (delete-file str-file-name)

str-file-name で与えられたファイルを削除します。 ファイルの削除に成功すると、true が返ります。
Deletes a file given in str-file-name. Returns true if the file was deleted successfully.

失敗した時、関数は nil を返します。 エラー情報については、ファイルに対して使った時は sys-error を使ってください。 URL の場合は net-error が詳細なエラー情報を与えてくれます。
On failure the function returns nil. For error information, use sys-error when used on files. When used on URLs net-error gives more error information.

ファイル名に URL を与えることもできます。
The file name can be given as a URL.

(delete-file "junk")

(delete-file "http://asite.com/example.html")

(delete-file "file://aFile.txt")

最初の例はカレント・ディレクトリのファイル junk を削除します。 二番目の例はファイル指定に URL を使う方法を示しています。 この形式には追加のパラメータを与えることができます。 その詳細は、delete-url で見てください。
The first example deletes the file junk in the current directory. The second example shows how to use a URL to specify the file. In this form, additional parameters can be given. See delete-url for details.



delete-url

syntax: (delete-url str-url)

この関数は、リモート HTTP サーバー上の str-url で指定されるファイルを削除します。 目的のウェブ・サーバー上で HTTP DELETE プロトコルが実行可能である必要がありますが、エラー・メッセージ文字列が返されるかもしれません。 目的のファイルにはアクセス許可も設定されていなければなりません。 タイムアウトやカスタム・ヘッダーのような追加のパラメータは、関数 get-url と同じく利用できます。
This function deletes the file on a remote HTTP server specified in str-url. The HTTP DELETE protocol must be enabled on the target web server, or an error message string may be returned. The target file must also have access permissions set accordingly. Additional parameters such as timeout and custom headers are available exactly as in the get-url function.

str-urlfile:// で始まっていれば、ローカル・ファイル・システム上のファイルが削除されます。
If str-url starts with file:// a file on the local file system is deleted.

この機能には関数 delete-file が使われ、URL にファイル名を指定することもできます。
This feature is also available when the delete-file function is used and a URL is specified for the filename.

(delete-url "http://www.aserver.com/somefile.txt")
(delete-url "http://site.org:8080/page.html" 5000)

; delete on the local file system
(delete-url "file:///home/joe/somefile.txt")

二番目の例は、5 秒のタイムアウト・オプションを指定しています。 特殊 HTTP プロトコル・ヘッダーのような他のオプションも指定可能です。 その詳細は、関数 get-url で見てください。
The second example configures a timeout option of five seconds. Other options such as special HTTP protocol headers can be specified, as well. See the get-url function for details.

delete-url 要求リクエストは newLISP のサーバー・モードで解釈されますが、サーバーが -http-safe モードで始まっている時は実行されません。
delete-url requests are also understood by newLISP server nodes, but will not be served when the server is started in -http-safe mode.



destroy

syntax: (destroy int-pid)
syntax: (destroy int-pid int-signal)

int-pid で指定するプロセス ID のプロセスを破棄し、成功すると true、失敗すると nil を返します。 プロセス ID は通常、macOS や 他の Unix 上で先に呼び出された fork か、全プラットフォーム上での process 呼び出しで得られます。 Unix 上の destroy は、SIGKILL シグナルを使うシステム・ユーティリティ kill のように動作します。
Destroys a process with process id in int-pid and returns true on success or nil on failure. The process id is normally obtained from a previous call to fork on macOS and other Unix or process on all platforms. On Unix, destroy works like the system utility kill using the SIGKILL signal.

注意! int-pid0 ならば、送り側のプロセス・グループ ID と同じグループ ID の全てのプロセスにシグナルが送られます。 int-pid-1 ならば、カレント・ユーザ ID の全プロセスが終了され、newLISP がスーパー・ユーザ特権モードで開始されていたなら、システム・プロセス以外の全プロセスが破棄されます。
CAUTION! If int-pid is 0 the signal is sent to all processes whose group ID is equal to the process group ID of the sender. If int-pid is -1 all processes with the current user id will be killed, if newLISP is started with super user privileges, all processes except system processes are destroyed.

int-signal を指定した時、destroyint-pid のプロセスに指定された Unix シグナルを送る Unix kill コマンドのように動作します。 この第二構文は MS Windows では利用できません。
When specifying int-signal, destroy works like a Unix kill command sending the specified Unix signal to the process in int-pid. This second syntax is not available on MS Windows.

(set 'pid (process "/usr/local/bin/bc" bcin bcout)) 
(destroy pid)

(set 'pid (fork (dotimes (i 1000) (println i) (sleep 10))))
(sleep 100) (destroy pid)


det

syntax: (det matrix [float-pivot])

正方行列の行列値を返します。行列は、入れ子リストと アレイ のどちらも可能です。
Returns the determinant of a square matrix. A matrix can either be a nested list or an array.

オプションで、0.0 か非常に小さい値を float-pivot に指定できます。 特異行列(訳注:逆行列を持たない行列)を処理するとゼロになるLU分解アルゴリズムにおいて、この値はピボット要素の代わりになります。
Optionally 0.0 or a very small value can be specified in float-pivot. This value substitutes pivot elements in the LU-decomposition algorithm, which result in zero when the algorithm deals with a singular matrix.

(set 'A '((-1 1 1) (1 4 -5) (1 -2 0)))
(det A)   -1

; treatment of singular matrices
(det '((2 -1) (4 -2)))         nil
(det '((2 -1) (4 -2)) 0)       -0
(det '((2 -1) (4 -2)) 1e-20)   -4e-20

行列が特異行列(訳注:逆行列を持たない行列)で float-pivot が指定されていなければ、nil が返ります。
If the matrix is singular and float-pivot is not specified, nil is returned.

他の行列操作 invertmatmultiplytranspose も見てください。
See also the other matrix operations invert, mat, multiply and transpose.


device

syntax: (device [int-io-handle])

int-io-handle は I/O デバイス番号で、デフォルトの標準 I/O ハンドル・ペア の 0(ゼロ)に設定されます。この場合、stdin が 0、stdout が 1 、stderr が 2 です。 int-io-handleopen を使って先に得られているファイル・ハンドルでもあります。 どちらの場合でも、このハンドルを通して入力と出力が割り当てられます。 引数がない時は、現在のI/Oデバイス番号が返ります。
int-io-handle is an I/O device number, which is set to 0 (zero) for the default STD I/O pair of handles, 0 for stdin, 1 for stdout and 2 for stderr. int-io-handle may also be a file handle previously obtained using open. In this case both, input and output are channeled through this handle. When no argument is supplied, the current I/O device number is returned.

device で指定される I/O チャンネルは、関数 printprintlnwritewrite-lineread-charread-line の内部で使われます。 現在の I/O デバイスが 0 か 1 の時は、print は出力をコンソール・ウィンドウに送り、read-line はキーボードから入力を受け取ります。 現在の I/O デバイスが開いているファイルに設定されているなら、printread-line は、そのファイルに対して動作します。
The I/O channel specified by device is used internally by the functions print, println, write, write-line and read-char, read-line. When the current I/O device is 0 or 1, print sends output to the console window and read-line accepts input from the keyboard. If the current I/O device has been set by opening a file, then print and read-line work on that file.

注記:Unix のようなオペレーティング・システムでは、標準入出力にチャンネル 0 を出力で、チャンネル 1 を入力で使うこともできます。 それに対し Windows では、標準入力が 0 で標準出力が 1 と厳密に決まっています。
Note, that on Unix like operating systems, stdin channel 0 can also be used for output and stdout channel 1 can also be used for reading input. This is not the case on Windows, where 0 is strictly for input and stdout 1 strictly for output.

(device (open "myfile" "write"))   5
(print "This goes in myfile")      "This goes in myfile"
(close (device))                   true

deviceclose を使うと、device は自動的に 0(ゼロ)にリセットされますので、注意してください。
Note that using close on device automatically resets device to 0 (zero).



difference

syntax: (difference list-A list-B)
syntax: (difference list-A list-B bool)

第一構文の difference は、list-Alist-B 間の集合 差を返します。 結果のリストは、list-A に在って、list-B に無い要素のみ持ちます。 結果のリストの全要素は単一(訳注:重複する要素が無い)ですが、list-Alist-B が単一である必要はありません。 リストの要素には Lisp 式のいかなる型もなれます。
In the first syntax, difference returns the set difference between list-A and list-B. The resulting list only has elements occurring in list-A, but not in list-B. All elements in the resulting list are unique, but list-A and list-B need not be unique. Elements in the lists can be any type of Lisp expression.

(difference '(2 5 6 0 3 5 0 2) '(1 2 3 3 2 1))   (5 6 0)

第二構文の differenceリスト モードで動作します。 booltruenil 以外に評価される式です。 結果のリストでは、list-A から list-B の全要素が取り除かれますが、list-A で重複している要素は残ります。
In the second syntax, difference works in list mode. bool specifies true or an expression not evaluating to nil. In the resulting list, all elements of list-B are eliminated in list-A, but duplicates of other elements in list-A are left.

(difference '(2 5 6 0 3 5 0 2) '(1 2 3 3 2 1) true)   (5 6 0 5 0)

集合関数 intersectuniqueunion も見てください。
See also the set functions intersect, unique and union.



directory

syntax: (directory [str-path])
syntax: (directory str-path str-pattern [regex-option])

str-path で与えたディレクトリ・パスのディレクトリ・エントリ名のリストが返ります。 失敗すると、nil が返ります。 str-path が省略されると、カレント・ディレクトリのエントリのリストが返ります。
A list of directory entry names is returned for the directory path given in str-path. On failure, nil is returned. When str-path is omitted, the list of entries in the current directory is returned.

(directory "/bin")

(directory "c:/")

最初の例は /bin のディレクトリを返し、二番目の例はドライブCのルート・ディレクトリのディレクトリ・エントリのリストを返します。 MS Windows システムでも、フォーワード・スラッシュ (/) がパス名に使えることに注目してください。 バックスラッシュ (\) を使う時は、二つの目のバックスラッシュの前置きが必要です。
The first example returns the directory of /bin, the second line returns a list of directory entries in the root directory of drive C:. Note that on MS Windows systems, a forward slash (/) can be included in path names. When used, a backslash (\) must be preceded by a second backslash.

第二構文の directory では、str-pattern の正規表現パターンをとることができます。 ディレクトリ・エントリのリスト中で、パターンに一致するファイル名だけが返ります。 regex-option で特殊正規表現オプションを指定できます。 (訳注:正規表現オプションの)詳細は regex で見てください。
In the second syntax, directory can take a regular expression pattern in str-pattern. Only filenames matching the pattern will be returned in the list of directory entries. In regex-option, special regular expression options can be specified; see regex for details.

(directory "." "\\.c")   ("foo.c" "bar.c")
;; or using braces as string pattern delimiters
(directory "." {\.c})   ("foo.c" "bar.c")

; show only hidden files (starting with dot)
(directory "." "^[.]")    ("." ".." ".profile" ".rnd" ".ssh")

正規表現は directory に対して、ファイル名に ".c" を持つもののみ返すことを強います。
The regular expression forces directory to return only file names containing the string ".c".

正規表現の使える他の関数には、findfind-allparseregexreplacesearch があります。
Other functions that use regular expressions are find, find-all, parse, regex, replace, and search.



directory?

syntax: (directory? str-path)

str-path がディレクトリかどうかをチェックします。 結果により、truenil が返ります。
Checks if str-path is a directory. Returns true or nil depending on the outcome.

(directory? "/etc")              true
(directory? "/usr/local/bin/emacs/")   nil


display-html JS

syntax: (display-html str-html)
syntax: (display-html str-html bool-flag)

この関数を第一構文で使うと、ブラウザの現在のページを str-html の中にある HTML のページで置き換えます。 HTML のページには、JavaScript を含めることもできます。
Using the first syntax, the function replaces the current page in the browser with the HTML page found in str-html.

bool-flagtrue に評価されると、ページ用に新しいブラウザ・タブが開かれので、現在のページは影響を受けません。
If the bool-flag evaluates to true, the page gets opened in a new browser tab and the current page is not affected.

この関数は JavaScript にコンパイルされた newLISP でのみ、利用できます。
This function is only available on newLISP compiled to JavaScript.

(set 'page [text]
<html>
<head>
<title>Hello App</title>
</head>
<body>
<h2>Hello World</h2>
</body>
</html>
[/text])

(display-html page true)  "92"

この関数は HTML 文書の文字列としての長さとして返します。(訳注:バイト単位でなく、文字単位です。)
The function returns the length of the HTML document displayed as a string.

現在のページで JavaScript を評価する関数 eval-string-js も見てください。
See also the function eval-string-js for evaluation of JavaScript in the current page.



div

syntax: (div num-1 num-2 [num-3 ... ])
syntax: (div num-1)

num-1num-2 以下の数値で連続的に除算します。 div は(訳注:整数と浮動小数点数の)混在型算術が可能ですが、戻り値は常に浮動小数点数です。 NaN(not a number) になる浮動小数点計算には NaN を返します。
Successively divides num-1 by the number in num-2—. div can perform mixed-type arithmetic, but it always returns floating point numbers. Any floating point calculation with NaN also returns NaN.

(div 10 3)                  3.333333333
(div 120 (sub 9.0 6) 100)   0.4

(div 10)                    0.1

引数が num-1 のみの時、divnum-1 の逆数を計算します。
When num-1 is the only argument, div calculates the inverse of num-1.



do-until

syntax: (do-until exp-condition [body])

exp-condition が評価される前に body 中の式群が評価されます。 exp-condition の評価が nil 以外なら do-until 式は終了し、そうでなければ body 中の式群が再び評価されます。 until が本体式群の評価の前に 条件式を評価するのに対して、do-until は本体の式群の評価の後に 条件式を評価しますので、注意してください。 do-until 式の戻り値は、本体式群の最後の評価です。 body が空なら、exp-condition の最後の結果が返ります。
The expressions in body are evaluated before exp-condition is evaluated. If the evaluation of exp-condition is not nil, then the do-until expression is finished; otherwise, the expressions in body get evaluated again. Note that do-until evaluates the conditional expression after evaluating the body expressions, whereas until checks the condition before evaluating the body. The return value of the do-until expression is the last evaluation of the body expression. If body is empty, the last result of exp-condition is returned.

do-until は、システムの反復シンボル $idx も更新します。
do-until also updates the system iterator symbol $idx.

(set 'x 1)
(do-until (> x 0) (inc x))
x   2

(set 'x 1)
(until (> x 0) (inc x))
x   1

(訳注:上記例では、)do-until が最低一回はループを通るのに対して、until はループに入りません。
While do-until goes through the loop at least once, until never enters the loop.

関数whiledo-while も見てください。
See also the functions while and do-while.



do-while

syntax: (do-while exp-condition body)

exp-condition が評価される前に body 中の式群が評価されます。 exp-condition の評価が nil なら do-while 式は終了し、そうでなければ body 中の式群が再び評価されます。 while が本体を評価する前 に条件をチェックするのに対して、do-while は本体式群を評価した後 に条件式を評価します。
The expressions in body are evaluated before exp-condition is evaluated. If the evaluation of exp-condition is nil, then the do-while expression is finished; otherwise the expressions in body get evaluated again. Note that do-while evaluates the conditional expression after evaluating the body expressions, whereas while checks the condition before evaluating the body. The return value of the do-while expression is the last evaluation of the body expression.

do-while は、システムの反復シンボル $idx も更新します。
do-while also updates the system iterator symbol $idx.

(set 'x 10)
(do-while (< x 10) (inc x))
x   11

(set 'x 10)
(while (< x 10) (inc x)) 
x   10

(訳注:上記例では、)do-while が最低一回はループを通るのに対して、while はループに入りません。
While do-while goes through the loop at least once, while never enters the loop.

関数untildo-until も見てください。
See also the functions until and do-until.



doargs

syntax: (doargs (sym [exp-break]) body)

ユーザ定義関数やマクロの中で引数リストの総数分、繰り返します。 このような関数やマクロは definedefine-macrolambdalambda-macro を使って定義できます。 引数リストが空になるか、(exp-breakに定義される)オプションの脱出条件が true か論理的真値に評価されるまで、sym の変数に引数リストの要素が次々にセットされます。 doargs 式は、最後の評価結果を返します。
Iterates through all members of the argument list inside a user-defined function or macro. This function or macro can be defined using define, define-macro, lambda, or lambda-macro. The variable in sym is set sequentially to all members in the argument list until the list is exhausted or an optional break expression (defined in exp-break) evaluates to true or a logical true value. The doargs expression always returns the result of the last evaluation.

doargs は、システムの反復シンボル $idx も更新します。
doargs also updates the system iterator symbol $idx.

(define (foo)
    (doargs (i) (println i)))

> (foo 1 2 3 4)
1
2
3
4

オプションの脱出条件は、doargs に引数操作の中断を引き起こします:
The optional break expression causes doargs to interrupt processing of the arguments:

(define-macro (foo)
    (doargs (i (= i 'x)) 
        (println i)))

> (foo a b x c d e)
a
b
true

引数リストの全てを一度にアクセスするためには、関数 args を使ってください。
Use the args function to access the entire argument list at once.



dolist

syntax: (dolist (sym list|array [exp-break]) body)

listarray の各要素毎に body の式群が評価されます。 本体式群が評価される前に、変数 sym にはリストの各要素にセットされます。 ループ・インデックスとして使われる変数(訳注:変数 sym のこと)は、局所変数でダイナミック・スコープの規則に従って振舞います。
The expressions in body are evaluated for each element in list or array. The variable in sym is set to each of the elements before evaluation of the body expressions. The variable used as loop index is local and behaves according to the rules of dynamic scoping.

オプションの exp-break に早期ループ脱出条件を定義できます。 中断式が nil 以外に評価されると、dolist ループは exp-break の値を返します。 中断条件は、body を評価する前に試されます。
Optionally, a condition for early loop exit may be defined in exp-break. If the break expression evaluates to any non-nil value, the dolist loop returns with the value of exp-break. The break condition is tested before evaluating body.

(set 'x 123)
(dolist (x '(a b c d e f g))  ; prints: abcdefg
    (print x))   g          ; return value

(dolist (x '(a b c d e f g) (= x 'e))  ; prints: abcd
    (print x))

;; x is local in dolist
;; x has still its old value outside the loop

x   123  ; x has still its old value

この例は、コンソール・ウィンドウに abcdefg を表示します。 dolistx はローカル・スコープなので、dolist が実行された後で x の値は変化せずに残ります。 dolist の戻り値は、最後に評価される式の結果です。
This example prints abcdefg in the console window. After the execution of dolist, the value for x remains unchanged because the x in dolist has local scope. The return value of dolist is the result of the last evaluated expression.

内部システム変数 $idx は、dolist に渡されたリストの現在のオフセットを保持し、実行中にアクセス可能です:
The internal system variable $idx keeps track of the current offset into the list passed to dolist, and it can be accessed during its execution:

(dolist (x '(a b d e f g))
  (println $idx ":" x))   g

0:a
1:b
2:d
3:e
4:f
5:g

太字がコンソール・アウトプットです。 $idx はプロテクトされていて、ユーザが変更することはできません。
The console output is shown in boldface. $idx is protected and cannot be changed by the user.



dostring utf8

syntax: (dostring (sym string [exp-break]) body)

string の各キャラクタ毎に body の式群が評価されます。 本体式群が評価される前に、変数 sym には 各 ASCII 値 か UTF-8 の整数値がセットされます。 ループ・インデックスとして使われる変数(訳注:変数 sym のこと)は、局所変数でダイナミック・スコープの規則に従って振舞います。
The expressions in body are evaluated for each character in string. The variable in sym is set to each ASCII or UTF-8 integer value of the characters before evaluation of the body expressions. The variable used as loop index is local and behaves according to the rules of dynamic scoping.

オプションの exp-break に早期ループ脱出条件を定義できます。 中断式が nil 以外に評価されると、dostring ループは exp-break の値を返します。 中断条件は、body を評価する前に試されます。
Optionally, a condition for early loop exit may be defined in exp-break. If the break expression evaluates to any non-nil value, the dolist loop returns with the value of exp-break. The break condition is tested before evaluating body.

; ASCII example
(set 'str "abcdefg")
(dostring (c str) (println c " - " (char c)))

97 - a
98 - b
99 - c
100 - d
101 - e
102 - f
103 - g

; UTF8 example
(set 'utf8str "我能吞下玻璃而不伤身体。")
(dostring (c utf8str) (println c " - " (char c)))

25105 - 我
33021 - 能
21534 - 吞
 ...
20307 - 体
12290 - 。 

この例では、コンソール・ウィンドウに各キャラクタの値が表示されます。 UTF-8 が使えるバージョンの newLISP では、個々のキャラクタが 1 バイトより大きくてループ変数の数値も 255 を超えるかもしれません。 dostring の戻り値は、最後に評価される式の結果です。
This example prints the value of each character in the console window. In UTF-8 enabled versions of newLISP, individual characters may be longer than one byte and the number in the loop variable may exceed 255. The return value of dostring is the result of the last evaluated expression.

内部システム変数 $idx は、dostring に渡された文字列の現在のオフセットを保持し、実行中にアクセス可能です。
The internal system variable $idx keeps track of the current offset into the string passed to dostring, and it can be accessed during its execution.



dotimes

syntax: (dotimes (sym-var int-count [exp-break]) body)

body の式群が int 回評価されます。 本体式(群)が評価される前に、変数sym-var には 0 (zero) から (int - 1) までがセットされます。 ループ・インデックスとして使われる変数(訳注:変数 sym-var のこと)は dotimes での局所変数で、ダイナミック・スコープの規則に従って振舞います。 ループ・インデックスは整数型です。 dotimes は、body 中、最後に評価された式の結果を返します。 dotimes 宣言文の評価が終わった後、sym-var は以前の値になります。
The expressions in body are evaluated int times. The variable in sym is set from 0 (zero) to (int - 1) each time before evaluating the body expression(s). The variable used as the loop index is local to the dotimes expression and behaves according the rules of dynamic scoping. The loop index is of integer type. dotimes returns the result of the last expression evaluated in body. After evaluation of the dotimes statement sym assumes its previous value.

オプションの exp-break に早期ループ脱出条件を定義できます。 中断式が nil 以外に評価されると、dotimes ループは exp-break の値を返します。 中断条件は、body を評価する前に試されます。
Optionally, a condition for early loop exit may be defined in exp-break. If the break expression evaluates to any non-nil value, the dotimes loop returns with the value of exp-break. The break condition is tested before evaluating body.

(dotimes (x 10)
  (print x))   9  ; return value

これは、コンソール・ウィンドウに 0123456789 を表示します。
This prints 0123456789 to the console window.



dotree

syntax: (dotree (sym sym-context [bool]) body)

sym-context の全シンボルで、body の式群が評価されます。 シンボルはソート順にアクセスされます。 本体の式(群)が各々評価される前に、変数sym には sym-context からのシンボルが次々とセットされます。 ループ・インデックスとして使われる変数(訳注:変数 sym のこと)は dotree での局所変数で、ダイナミック・スコープの規則に従って振舞います。
The expressions in body are evaluated for all symbols in sym-context. The symbols are accessed in a sorted order. Before each evaluation of the body expression(s), the variable in sym is set to the next symbol from sym-context. The variable used as the loop index is local to the dotree expression and behaves according the rules of dynamic scoping.

オプションの bool 式が nil 以外に評価されると、アンダースコア・キャラクタ _ の付いたシンボル文字列のみがアクセスされます。 アンダースコア _ で始まるシンボル名は、hash keysbayes-train で作られるシンボルです。
When the optional bool expression evaluates to not nil, only symbols starting with an underscore character _ are accessed. Symbol names starting with an _ underscore are used for hash keys and symbols created by bayes-train.

dotree も、システム反復変数 $idx を更新します。
dotree also updates the system iterator symbol $idx.

;; faster and less memory overhead
(dotree (s SomeCTX) (print s " "))

;; slower and higher memory usage
(dolist (s (symbols SomeCTX)) (print s " "))

この例は、SomeCTX 内の全シンボル名をコンソール・ウィンドウに表示します。
This example prints the names of all symbols inside SomeCTX to the console window.



dump

syntax: (dump [exp])

newLISP セルのバイナリ・データを表示します。 この関数に引数を与えないと、全ての Lisp セルがコンソールにリスト表示されます。 exp が与えられると、それが評価され、その Lisp セルの中身が(訳注:バイナリ・データの)リストで返ります。
Shows the binary contents of a newLISP cell. Without an argument, this function outputs a listing of all Lisp cells to the console. When exp is given, it is evaluated and the contents of a Lisp cell are returned in a list.

(dump 'a)    (9586996 5 9578692 9578692 9759280)

(dump 999)   (9586996 130 9578692 9578692 999)

このリストには、下記に示すメモリ・アドレスと情報が含まれます:
The list contains the following memory addresses and information:

offsetdescription(詳細)
0newLIPセルのメモリ・アドレス
memory address of the newLISP cell
1cell->type:
    major/minor 型、詳細は newlisp.h を見てください。
    major/minor type, see newlisp.h for details
2cell->next:
    リスト・ポインタへのリンク
    linked list ptr
3cell->aux:
    文字列の長さ+1か、
    64ビット整数のロー(リトル・エンディアン)またはハイ(ビッグ・エンディアン)ワードか、
    IEEE 754 倍精度浮動書数点数のロー・ワード
    string length+1 or
    low (little endian) or high (big endian) word of 64-bit integer or
    low word of IEEE 754 double float
4cell->contents:
    文字列/シンボルのアドレスか、
    64ビット整数のハイ(リトル・エンディアン)またはロー(ビッグ・エンディアン)ワードか、
    IEEE 754 倍精度浮動書数点数のハイ・ワード
    string/symbol address or
    high (little endian) or low (big endian) word of 64-bit integer or
    high word of IEEE 754 double float

この関数は、セルの型ビットを変更したり、newLISP 内部をハックするのに役立ちます。 わかりやすい例として、関数 cpymem を見てください。
This function is valuable for changing type bits in cells or hacking other parts of newLISP internals. See the function cpymem for a comprehensive example.



dup

syntax: (dup exp int-n [bool])
syntax: (dup exp)

exp の式が文字列に評価されたなら、その文字列を int-n 回複製して返します。 nil 以外に評価される式を bool に指定すると、文字列は複製されますが連結されず、他のデータ型と同じようにリストになります。
If the expression in exp evaluates to a string, it will be replicated int-n times within a string and returned. When specifying an expression evaluating to anything other than nil in bool, the string will not be concatenated but replicated in a list like any other data type.

exp が文字列以外のデータ型の場合は、戻り値のリストには exp の評価値が int-n 個入ります。
If exp contains any data type other than string, the returned list will contain int-n evaluations of exp.

反復パラメータ無し時、dup は 2 を推定します。
Without the repetition parameter, dup assumes 2.

(dup "A" 6)        "AAAAAA"
(dup "A" 6 true)   ("A" "A" "A" "A" "A" "A")
(dup "A" 0)        ""
(dup "AB" 5)       "ABABABABAB"
(dup 9 7)          (9 9 9 9 9 9 9)
(dup 9 0)          ()
(dup 'x 8)         (x x x x x x x x)
(dup '(1 2) 3)     ((1 2) (1 2) (1 2))
(dup "\000" 4)     "\000\000\000\000"

(dup "*")          "**"

最後のほうの例は、4つのバイナリ・ゼロで満たされる文字列を作るという、バイナリ・データの扱い方を示しています。
The last example shows handling of binary information, creating a string filled with four binary zeroes.

関数 sequenceseries も見てください。
See also the functions sequence and series.



empty?

syntax: (empty? exp)
syntax: (empty? str)

exp が空のリスト(あるいは、str が空の文字列)かどうかを試します。 引数に要素を含んでいるかどうかで、truenil が返ります。
exp is tested for an empty list (or str for an empty string). Depending on whether the argument contains elements, true or nil is returned.

(set 'var '())
(empty? var)          true
(empty? '(1 2 3 4))   nil
(empty? "hello")      nil
(empty? "")           true

最初の例はリストをチェックし、次の二つは文字列をチェックしています。
The first example checks a list, while the second two examples check a string.



encrypt

syntax: (encrypt str-source str-pad)

暗号帳となる文字列エンクリプション・パッド str-pad を使って、一回限りの暗号帳ワンタイム・パッド (OTP) で str-source を暗号化します。 str-pad が長くて、バイト列がランダムであればあるほど、暗号は安全になります。 暗号帳となる文字列エンクリプション・パッドがソース・テキストより長ければ、完全にランダムに一回だけ使われることになります。 つまり、一回限りの暗号帳ワンタイム・パッドで暗号化されたデータは一見ランダムなデータのように見えるので、ほとんど解読不可能になります。 オリジナルの復元には、同じ関数と暗号帳となる文字列エンクリプション・パッドを暗号化されたテキストに適用します:
Performs a one-time pad (OTP) encryption of str-source using the encryption pad in str-pad. The longer str-pad is and the more random the bytes are, the safer the encryption. If the pad is as long as the source text, is fully random, and is used only once, then one-time–pad encryption is virtually impossible to break, since the encryption seems to contain only random data. To retrieve the original, the same function and pad are applied again to the encrypted text:

(set 'secret 
  (encrypt "A secret message" "my secret key")) 
 ",YS\022\006\017\023\017TM\014\022\n\012\030E"

(encrypt secret "my secret key")   "A secret message"

二番目の例は、ファイルを丸ごと暗号化しています:
The second example encrypts a whole file:

(write-file "myfile.enc" 
  (encrypt (read-file "myfile") "29kH67*"))


ends-with

syntax: (ends-with str-data str-key [num-option])
syntax: (ends-with list exp)

第一構文の ends-with は、str-data の文字列が str-key で指定された文字列で終わるかどうかをテストします。 結果次第で、truenil が返ります。
In the first syntax, ends-with tests the string in str-data to see if it ends with the string specified in str-key. It returns true or nil depending on the outcome.

正規表現 option 番号が指定されると、str-key に正規表現パターンが使えます。 option で使える番号は regex で見てください。
If a regular expression option number is specified, str-key contains a regular expression pattern. See regex for valid numbers for option.

(ends-with "newLISP" "LISP")          true
(ends-with "newLISP" "lisp")          nil
;; use regular expressions
(ends-with "newLISP" "lisp|york" 1)   true

第二構文の ends-with は、(訳注:list の)リストが exp のリスト要素で終わっているかどうかをチェックします。 結果次第で、truenil が返ります。
In the second syntax, ends-with checks if a list ends with the list element in exp. true or nil is returned depending on outcome.

(ends-with '(1 2 3 4 5) 5)              true
(ends-with '(a b c d e) 'b)             nil
(ends-with '(a b c (+ 3 4)) '(+ 3 4))   true

最後の例は、exp にリスト自身も使えることを示しています。
The last example shows that exp could be a list by itself.

関数 starts-with も見てください。
See also the starts-with function.



env

syntax: (env)
syntax: (env var-str)
syntax: (env var-str value-str)

第一構文(引数無し)は、オペレーティング・システム環境の各エントリーを連想リストとして取り出します。連想リストは、環境変数とその値がキー・値対になります。
In the first syntax (without arguments), the operating system's environment is retrieved as an association list in which each entry is a key-value pair of environment variable and value.

(env)  
 (("PATH" "/bin:/usr/bin:/sbin") ("TERM" "xterm-color") ... ))

第二構文では、var-str を環境変数に与えます。 env は変数の値を返すか、変数が環境に無い場合の nil を返します。
In the second syntax, the name of an environment variable is given in var-str. env returns the value of the variable or nil if the variable does not exist in the environment.

(env "PATH")   "/bin:/usr/bin:/usr/local/bin"

第三構文(変数名 var-str と対になる値 value-str)は、環境変数を設定するか、新規に作成します。 value-str が空文字列 "" なら、変数は環境から完全に削除されますが、Solaris 上で動作している時は、空の文字列が設定されます。
The third syntax (variable name in var-str and value pair in value-str) sets or creates an environment variable. If value-str is the empty string "", then the variable is completely removed from the environment except when running on Solaris, where the variable stays with an empty string.

(env "NEWLISPBIN" "/usr/local/bin/")   true
(env "NEWLISPBIN")               "/usr/local/bin/"
(env "NEWLISPBIN" "")            true
(env "NEWLISPBIN")               nil


erf

syntax: (erf num)

erf は、num の値の誤差関数を計算します。 誤差関数は、次のように定義されます:
erf calculates the error function of a number in num. The error function is defined as:

erf (x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt

(map erf (sequence 0.0 6.0 0.5))
 
(0 0.5204998778 0.8427007929 0.9661051465 0.995322265 0.999593048 
 0.9999779095 0.9999992569 0.9999999846 0.9999999998 1 1 1) 


error-event

syntax: (error-event sym-event-handler | func-event-handler)
syntax: (error-event nil)

sym-event-handler には、エラー操作のためのユーザ定義関数が入ります。 エラーが発生するとシステムは reset を実行し、ユーザ・エラー・ハンドラを実行します。 エラー・ハンドラでは、エラー番号とテキストを取り出すために、組込関数last-error が使えます。 イベント・ハンドラには、クォート付きのシンボルかラムダ関数を指定します。
sym-event-handler contains a user-defined function for handling errors. Whenever an error occurs, the system performs a reset and executes the user-defined error handler. The error handler can use the built-in function last-error to retrieve the number and text of the error. The event handler is specified as either a quoted symbol or a lambda function.

error-event をキャンセルするには、第二構文を使ってください。
To cancel error-event, use the second syntax.

(define (my-handler)    
  (print "error # " (first (last-error)) " has occurred\n") )

(error-event 'my-handler)   my-handler

;; specify a function directly

(error-event my-handler)   $error-event

(error-event 
  (fn () (print "error # " (first (last-error)) " has occurred\n")))

(error-event exit)   $error-event

エラーを扱う別の方法としては、catch を見てください。 ユーザ定義エラーを起こすには、 throw-error を使ってください。
For a different way of handling errors, see the catch function. Use throw-error to throw user-defined errors.



eval

syntax: (eval exp)

evalexp の評価結果を現変数環境で評価します。
eval evaluates the result of evaluating exp in the current variable environment.

(set 'expr '(+ 3 4))   (+ 3 4)
(eval expr)            7
(eval (list + 3 4))    7
(eval ''x)             x
(set 'y 123)          
(set 'x 'y)           
x             y
(eval x)      123

通常、変数の評価は現変数環境下で起こります:
As usual, evaluation of variables happens in the current variable environment:

; eval in global (top level) environment
(set 'x 3 'y 4)
(eval '(+ x y))           7

; eval in local environment
(let ( (x 33) (y 44) ) 
    (eval '(+ x y)))      77

; old environment after leaving local let environment
(eval '(+ x y))           7

newLISP は全ての引数を値で渡します。 クォート付きシンボルを使うと、シンボルを通した参照として式を渡すことができます。 つまり、シンボルの元の内容にアクセスするために eval が使えます:
(訳注:つまり、マクロを使わずに破壊的関数を書くことができる)
newLISP passes all arguments by value. Using a quoted symbol, expressions can be passed by reference through the symbol. eval can be used to access the original contents of the symbol:

(define (change-list aList) (push 999 (eval aList)))

(set 'data '(1 2 3 4 5))

(change-list 'data)   (999 1 2 3 4 5)

例では、パラメータ 'data はクォート付ですので、push は元のリスト上で動作します。
In the example, the parameter 'data is quoted, so push can work on the original list.

コンテキスト・オブジェクト内にデータを内包する newLISP で、これは参照により引数を渡す安全な方法です。 参照によるデータの受け渡し の章を見てください。 名前空間を使ったユーザ定義関数に参照を渡すことは、渡されたシンボルが関数のパラメータとして使われている名前と同じ場合に起こりうるシンボル渡し時の変数補足 を避けます。
There is a safer method to pass arguments by reference in newLISP by enclosing the data inside context objects. See the chapter Passing data by reference. Passing references into user defined function using namespace ids avoids variable capture of the passed symbol, in case the symbol passed is the same used as a parameter in the function.



eval-string

syntax: (eval-string str-source [sym-context [exp-error [int-offset]]])

str-source の文字列が newLISP の内部形式にコンパイルされ、評価されます。 評価結果が返ります。 文字列が一つより多い式を含むなら、最後に評価された結果が返ります。
The string in str-source is compiled into newLISP's internal format and then evaluated. The evaluation result is returned. If the string contains more than one expression, the result of the last evaluation is returned.

文字列が解析・翻訳される際のコンテキストを指定するために、オプションの第二引数が使えます。
An optional second argument can be used to specify the context to which the string should be parsed and translated.

str-source の解析・評価中にエラーが発生すると、exp-error が評価され、結果が返ります。
If an error occurs while parsig and evaluating str-source then exp-error will be evaluated and the result returned.

int-offset はオプションで、str-source 内の評価を開始するオフセットを指定します。
int-offset specifies an optional offset into str-source, where to start evaluation.

(eval-string "(+ 3 4)")   7
(set 'X 123)              123
(eval-string "X")         123

(define (repl) ; read print eval loop
  (while true
    (println "=> " (eval-string (read-line) MAIN (last-error)))
  )
)

(set 'a 10)
(set 'b 20)
(set 'foo:a 11)
(set 'foo:b 22)

(eval-string "(+ a b)")        30
(eval-string "(+ a b)" 'foo)   33

二番目の例は、簡単な newLISP インタープリタ評価ループを示しています。
The second example shows a simple newLISP interpreter eval loop.

最後の例は、翻訳時に使いたいコンテキストを指定する方法を示しています。 これにより、シンボル abMAIN の代わりに、コンテキスト foo のシンボルとその値を参照します。
The last example shows how to specify a target context for translation. The symbols a and b now refer to symbols and their values in context foo instead of MAIN.

評価せずに文字列を翻訳する関数 read-expr も見てください。
See also the function read-expr which translates a string without evaluating it.



eval-string-js JS

syntax: (eval-string-js str-JavaScript-source)

この関数は str-JavaScript-source にある(訳注:JavaScriput の)プログラム・ソースを受け取り、結果を文字列で返します。
The function takes a program source in str-JavaScript-source and returns the result in a string.

この関数は JavaScript にコンパイルされた newLISP でのみ、利用できます。
This function is only available on newLISP compiled to JavaScript.

(eval-string-js "window.prompt('Enter some text:', '')")

; JavaScropt 関数に渡す文字列の中に
; シングル・クォートやダブル・クォートを含めるためには、
; 先付のバックスラッシュ \(訳注;日本語環境では円記号 ¥ )が必要ですので、
; 文字列全体を [text], [/text] タグで囲って eval-string-js に渡します。
; for single and double quotes inside a string passed to a
; JavaScropt function, single and double quotes must be
; preceded by a backslash \ and the whole string passed
; to eval-string-js limited by [text], [/text] tags.

(eval-string-js [text]alert('A double quote: \" and a single quote: \' ')[/text])

(eval-string-js "6 * 7")

最初の式は、テキストを入力するダイアログをポップアップさせるでしょう。 そして、入力された文字列を返します。 二番目の式は、42 の文字列を返します。
The first expression will pop up a dialog box to enter text. The function will return the text string entered. The second expression will return the string 42.

ブラウザに HTML ページを表示する関数 display-html も見てください。
See also the function display-html for displaying an HTML page in the browser.



even?  bigint

syntax: (even? int-number)

整数値が 2ちょうど割り切れ 、余りが無いことをチェックします。 浮動小数点が int-number に渡された時は、小数部分を切り捨てた整数として扱われます。
Checks if an integer number is even divisible by 2, without remainder. When a floating point number is passed for int-number, it will be converted to an integer by cutting off its fractional part.

(even? 123)   nil
(even? 8)     true
(even? 8.7)   true

整数が 2 で割り切れないかどうかのチェックには、odd? を使ってください。
Use odd? to check if an integer is not divisible by 2.



exec

syntax: (exec str-process)
syntax: (exec str-process [str-stdin])

第一形式の exec は、str-process に記載されているプロセスを起動し、すべての標準出力を(標準出力(STDOUT)の各ライン毎に一つの)文字列のリストで返します。 プロセスを起動できなかった場合、execnil を返します。 プロセスが起動しても、改行のみやエラーや出力なしの場合は空リストが返ります。
In the first form, exec launches a process described in str-process and returns all standard output as a list of strings (one for each line in standard out (STDOUT)). exec returns nil if the process could not be launched. If the process could be launched but only returns and error and no valid output, the empty list will be returned.

(exec "ls *.c")   ("newlisp.c" "nl-math.c" "nl-string.c")

この例は、プロセスを開始してシェル・コマンドls を実行し、文字列のアレイの出力を取り込みます。
The example starts a process and performs the shell command ls, capturing the output in an array of strings.

第二形式の exec は、パイプ・プロセスを生成し、プロセスの標準入力を str-stdin から受け取る str-process のプロセスを開始します。 起動に成功すれば、戻り値は true となり、そうでなければ nil となります。
In the second form, exec creates a process pipe, starts the process in str-process, and receives from str-stdin standard input for this process. The return value is true if the process was successfully launched; otherwise it is nil.

(exec "cgiProc" query)

この例では、cgiProc は cgi プロセッサ(例えば、Perl や newLISP)で変数 query 内の文字列に供給される標準入力を受け取り、処理します。
In this example, cgiProc could be a cgi processor (e.g., Perl or newLISP) that receives and processes standard input supplied by a string contained in the variable query.



exists

syntax: (exists func-condition list)

func-conditionlist の要素に次々と適用して、func-condition の条件に合う最初の要素を返します。 条件に合う要素がなければ、nil が返ります。
Successively applies func-condition to the elements of list and returns the first element that meets the condition in func-condition. If no element meets the condition, nil is returned.

(exists string? '(2 3 4 6 "hello" 7))        "hello"

(exists string? '(3 4 2 -7 3 0))             nil

(exists zero? '(3 4 2 -7 3 0))               0 ; check for 0 or 0.0

(exists < '(3 4 2 -7 3 0))                   -7 ; check for negative

(exists (fn (x) (> x 3)) '(3 4 2 -7 3 0))    4

(exists (fn (x) (= x 10)) '(3 4 2 -7 3 0))   nil 

func-conditionnil? ならば、結果の nil はどちらにでも取れます。 このような場合に、nil を見つけるより良い方法は indexfind です。
If func-condition is nil?, the result nil is ambiguous. In this case index or find are the better method when looking for nil.

リスト中の全ての要素が条件に合っているかどうかをチェックするには、関数 for-all を使います。
Use the for-all function to check if a condition is met for all elements in a list.



exit

syntax: (exit [int])

newLISP を終了します。 オプションの終了コード int が与えられます。 このコードは、ホストのオペレーティングシステムでテストされます。 newLISP がコマンド・ライン・オプション -d を使って デーモン・サーバー・モード で走っている時は、ネットワーク接続のみが閉じられ、newLISP はそのまま残り、新しい接続を待ちます。
Exits newLISP. An optional exit code, int, may be supplied. This code can be tested by the host operating system. When newLISP is run in daemon server mode using -d as a command-line option, only the network connection is closed, while newLISP stays resident, listening for a new connection.

(exit 5)


exp

syntax: (exp num)

num の式が評価され、その結果のもとに(訳注:底が e の)指数関数を計算します。 explog の逆関数です。
The expression in num is evaluated, and the exponential function is calculated based on the result. exp is the inverse function of log.

(exp 1)         2.718281828
(exp (log 1))   1


expand

syntax: (expand exp sym-1 [sym-2 ... ])
syntax: (expand exp list-assoc [bool])
syntax: (expand exp)

第一構文では、sym(あるいは sym-2 から sym-nの複数シンボル)の一シンボルが、単純な式もしくは入れ子の式 exp 内で検索されます。 そして、検索されたシンボルの現在の束縛に展開され(訳注:exp 中の sym と同名のシンボルが sym の内容に置き換わる)、展開された式が返ります。元のリストは変化せずに残ります。
In the first syntax, one symbol in sym (or more in sym-2 through sym-n) is looked up in a simple or nested expression exp. They are then expanded to the current binding of the symbol and the expanded expression is returned. The original list remains unchanged.

(set 'x 2 'a '(d e))
(set 'foo 'a)
(expand foo 'a)                (d e)
(expand '(a x b) 'x)            (a 2 b)
(expand '(a x (b c x)) 'x)      (a 2 (b c 2))
(expand '(a x (b c x)) 'x 'a)   ((d e) 2 (b c 2))

expand は、ラムダ式を構成する時や内部書換マクロで変数を展開する時に役立ちます。
expand is useful when composing lambda expressions or doing variable expansion as in rewrite macros.

(define (raise-to power)
  (expand (fn (base) (pow base power)) 'power))

(define square (raise-to 2))
(define cube (raise-to 3))

(square 5)   25
(cube 5)     125

一個以上のシンボルがある時、expand はインクリメンタルに作用します:
If more than one symbol is present, expand will work in an incremental fashion:

(set 'a '(b c))
(set 'b 1)

(expand '(a b c) 'a 'b)   ((1 c) 1 c) 

関数 apply のように、expand は引数リストを畳み込み ます。
Like the apply function, expand reduces its argument list.

syntax: (expand list list-assoc [bool])

expand の第二構文は直接(訳注:連想リスト list-assoc で)指定された束縛の展開を許可しますので、関連する変数(訳注:連想リストの変数)において set を実行する必要はありません:
The second syntax of expand allows expansion bindings to be specified on the fly, without performing a set on the participating variables:

booltrue に評価されると、連想リストの値部分は評価されます。
If the bool evaluates to true, the value parts in the association list are evaluated.

(expand '(a b c) '((a 1) (b 2)))                 (1 2 c)
(expand '(a b c) '((a 1) (b 2) (c (x y z))))     (1 2 (x y z))
(expand '(a b) '((a (+ 1 2)) (b (+ 3 4))))       ((+ 1 2) (+ 3 4))
(expand '(a b) '((a (+ 1 2)) (b (+ 3 4))) true)  (3 7)

(訳注:booltrue でない時、)連想リストの変数の内容が変化しないことに注意してください。 これが、連想部分の評価と割り当てで変数が設定される関数 letex との違いです。
Note that the contents of the variables in the association list will not change. This is different from the letex function, where variables are set by evaluating and assigning their association parts.

expand のこの形式は、関数 unify との併用で論理プログラミングによく使われます。
This form of expand is frequently used in logic programming, together with the unify function.

syntax: (expand list)

第三構文は、大文字で始まる変数の内容を展開する時にのみ使われます。 この PROLOG モードは、論理プログラミング環境でも使われます。 expand の第一構文のように、シンボルは予めセットされていなければなりません。 大文字で nil 以外に束縛される変数のみが展開されます:
A third syntax is used to expand only the contents of variables starting with an uppercase character. This PROLOG mode may also be used in the context of logic programming. As in the first syntax of expand, symbols must be preset. Only uppercase variables and those bound to anything other than nil will be expanded:

(set 'A 1 'Bvar 2 'C nil 'd 5 'e 6)
(expand '(A (Bvar) C d e f))   (1 (2) C d e f)

大文字で始まり、nil でない中身を持つシンボル ABvar のみが展開されます。
Only the symbols A and Bvar are expanded because they have capitalized names and non-nil contents.

expand の第一構文を実演している例題の カリー化 関数は、大文字変数を使ってより簡単になります:
The currying function in the example demonstrating the first syntax of expand can now be written even more simply using an uppercase variable:

(define (raise-to Power) 
  (expand (fn (base) (pow base Power))))

> (define cube (raise-to 3))
(lambda (base) (pow base 3))

> (cube 4)
64

> _

展開機構を提供する関数 letexexpand と一緒によく使われる関数 unify も見てください。
See the letex function, which also provides an expansion mechanism, and the function unify, which is frequently used together with expand.



explode utf8

syntax: (explode str [int-chunk [bool]])
syntax: (explode list [int-chunk [bool]])

第一構文の explode は、文字列 (str) を一文字ずつの文字列リストに変換します。 オプションで、文字列を複数個の文字の集合に分けるために、集合サイズを int-chunk に指定できます。 bool の値が nil 以外の時、int-chunk で指定された長さを満たさない最後の集合は削除されます。
In the first syntax, explode transforms the string (str) into a list of single-character strings. Optionally, a chunk size can be specified in int-chunk to break the string into multi-character chunks. When specifying a value for bool other than nil, the last chunk will be omitted if it does not have the full length specified in int-chunk.

(explode "newLISP")   ("n" "e" "w" "L" "I" "S" "P")

(join (explode "keep it together"))   "keep it together"

(explode "newLISP" 2)     ("ne" "wL" "IS" "P")

(explode "newLISP" 3)     ("new" "LIS" "P")

; omit last chunk if too short
(explode "newLISP" 3 true)     ("new" "LIS")

UTF8版でなければ、explode はバイナリ・データにも作用します:
Only on non UTF8– enabled versions, explode also works on binary content:

(explode "\000\001\002\003") 
 ("\000" "\001" "\002" "\003")

UTF-8 版 newLISP で呼ばれた explode は、バイト境界ではなくキャラクタ境界で動作します。 UTF-8 エンコード文字列で、文字は 1 バイト以上から成っています。 (訳注:UTF-8 版 newLISP は、)ゼロ・バイト・キャラクタ(訳注:"\000")を見つけると処理を終了します。
When called in UTF-8–enabled versions of newLISP, explode will work on character boundaries rather than byte boundaries. In UTF-8–encoded strings, characters may contain more than one byte. Processing will stop when a zero byte character is found.

UTF-8 版 newLISP でバイナリ・データを展開したい時は、次の例で示される unpack を使ってください:
To explode binary contents on UTF-8–enabled versions of newLISP use unpack as shown in the following example:

(set 'str "\001\002\003\004")  "\001\002\003\004"

(unpack (dup "c" (length str)) str)  (1 2 3 4)
(unpack (dup "s" (length str)) str)  ("\001" "\002" "\003" "\004")
(訳例:unpack"c" オプションは符号付です。符号無しには "b" オプションを使います。
> (set 'str "\000\001\128\255")
"\000\001\128\255"
> (unpack (dup "c" (length str)) str)
(0 1 -128 -1)
> (unpack (dup "b" (length str)) str)
(0 1 128 255)
> 
上記例は、UTF-8 版でない newLISPを使っていますが、 動作は set 文の戻り値の表示以外は UTF-8 版 newLISPでも同じです。 )

第二構文の explode は、int-chunk の集合サイズのサブ・リストにリストを分解します。 int-chunk のデフォルトは 1 です。
In the second syntax, explode explodes a list (list) into sublists of chunk size int-chunk, which is 1 (one) by default.

次に示す例は、bool 値が nil 以外の時に、集合が int-chunk で指定された長さを満たさない最後の集合を削除するものです。
The following shows an example of the last chunk being omitted when the value for bool is other than nil, and the chunk does not have the full length specified in int-chunk.

(explode '(a b c d e f g h))     ((a) (b) (c) (d) (e) (f) (g) (h))
(explode '(a b c d e f g) 2)   ((a b) (c d) (e f) (g))

; omit last chunk if too short
(explode '(a b c d e f g) 2 true)   ((a b) (c d) (e f))

(transpose (explode '(a b c d e f g h) 2)) 
 ((a c e g) (b d f h))

関数 joinappendexplode 操作の逆操作です。
The join and append functions are inverse operations of explode.



extend !

syntax: (extend list-1 [list-2 ... ])
syntax: (extend string-1 [string-2 ... ])

list-1 のリストに list-2 が追加されて拡張されます。 一個以上のリストが追加されます。
The list in list-1 is extended by appending list-2. More than one list may be appended.

string-1 の文字列に string-2 が追加されて拡張されます。 一個以上の文字列が追加されます。 文字列には、バイナリ 0(ゼロ)文字を含めることができます。
The string in string-1 is extended by appending string-2. More than one string may be appended. The string can contain binary 0 (zero) characters.

第一パラメータには、初期化されていない変数も使えます。
The first parameter can be an un-initialized variable.

拡張されたリストまたは文字列を返します。
The extended list or string is returned.

; extending lists

(extend lst '(a b) '(c d))  (a b c d)
(extend lst '(e f g))  (a b c d e f)
lst  (a b c d e f g)

; extending strings

(extend str "ab" "cd")  "abcd"
(extend str "efg")  "abcdefg"
str  "abcdefg"

; extending in place

(set 'L '(a b "CD" (e f)))
(extend (L 2) "E")
L  (a b "CDE" (e f))

(extend (L 3) '(g))
L  (a b "CDE" (e f g))

リストや文字列の非破壊拡張には、append を見てください。
For a non-destructive list or string extension see append.



factor

syntax: (factor int)

int の数値を素因数分解します。 num が浮動小数点数なら、整数部分に切り捨てられます。
Factors the number in int into its prime components. Floating point numbers in num are truncated to their integer part.

(factor 123456789123456789)   (3 3 7 11 13 19 3607 3803 52579)

;; check correctness of factoring
(= (apply * (factor 123456789123456789)) 123456789123456789)
 true

;; factor the biggest integer
(factor 9223372036854775807)   (7 7 73 127 337 92737 649657)

;; primes.lsp - return all primes in a list, up to n 

(define (primes n , p)
  (dotimes (e n) 
    (if (= (length (factor e)) 1) 
      (push e p -1))) p)
           
(primes 20)   (2 3 5 7 11 13 17 19)         

factor2 より小さい数値で nil を返します。 浮動小数点数から変換された 9,223,372,036,854,775,807 (64ビット整数の最大値) より大きい数値は、整数の最大値で因数分解されます。
factor returns nil for numbers smaller than 2. For numbers larger than 9,223,372,036,854,775,807 (the largest 64-bit integer) converted from floating point numbers, the largest integer is factored.



fft

syntax: (fft list-num)

FFT (Fast Fourier Transform) 法を使って、list-num の複素数リストを離散的フーリエ変換します。 各複素数は実数部とそれに続く虚数部で指定されます。 実数部のみを使う場合は、虚数部は 0.0 (zero) にセットされます。 list-num の要素数が 2の倍数でない時、fft はゼロでリストを埋めて要素数を増やします。 複素数の虚数部が 0 の時は、複素数の代わりに単なる数値が使えます。
Calculates the discrete Fourier transform on the list of complex numbers in list-num using the FFT method (Fast Fourier Transform). Each complex number is specified by its real part followed by its imaginary part. If only real numbers are used, the imaginary part is set to 0.0 (zero). When the number of elements in list-num is not a power of 2, fft increases the number of elements by padding the list with zeroes. When the imaginary part of a complex number is 0, simple numbers can be used instead.

(ifft (fft '((1 0) (2 0) (3 0) (4 0)))) 
 ((1 0) (2 0) (3 0) (4 0))

;; when imaginary part is 0, plain numbers work, too
;; plain numbers and complex numbers can be intermixed

(fft '(1 2 3 4))       ((10 0) (-2 -2) (-2 0) (-2 2))
(fft '(1 2 (3 0) 4))   ((10 0) (-2 -2) (-2 0) (-2 2))

fft の逆操作は関数 ifft です。
The inverse operation of fft is the ifft function.



file-info

syntax: (file-info str-name [int-index [bool-flag]])

str_name のファイルかディレクトリの情報をリストで返します。 オプションのインデックスで、戻り値のリスト番号を指定できます。 bool-flag が指定されないか、nilに評価されると、ファイルがオリジナル・ファイルにリンクしていても、リンクの情報が返ります。 bool-flagnil 以外に評価されると、リンクで参照されるオリジナル・ファイルの情報が返されます。 (訳注:リンクは、MS Windows のショート・カットとは違います。 つまり、MS Windows で bool-flag オプションを使っても、何も変わりません。)
Returns a list of information about the file or directory in str_name. The optional index specifies the list member to return. When no bool-flag is specified or when bool-flag evaluates to nil information about the link is returned if the file is a link to an original file. If bool-flag evaluates to anything else than nil, information about the original file referenced by the link is returned.

offsetcontents
0サイズ
size
1mode (differs with true flag)
2device mode
3user ID
4group ID
5アクセス日時
access time
6更新日時
modification time
7作成日時
status change time

bool-flag の状態次第で、関数はリンク(フラグ無し、または、nil)か、リンクしているオリジナル・ファイル(true フラグ)のどちらかを報告します。
Depending on bool-flag set, the function reports on either the link (no flag or nil flag) or on the original linked file (true flag).

(file-info ".bashrc")   
 (124 33188 0 500 0 920951022 920951022 920953074)

(file-info ".bashrc" 0)   124

(date (file-info "/etc" -1))   "Mon Mar 8 18:23:17 2005"

二番目の例では、最後のディレクトリ /etc の作成日時が取り出されています。
In the second example, the last status change date for the directory /etc is retrieved.

file-infomode 部を除いて、リンクではなく、リンクされているファイルのファイル統計値 (サイズ) を与えます。
file-info gives file statistics (size) for a linked file, not the link, except for the mode field.



file?

syntax: (file? str-path-name [bool])

str-name のファイルの存在をチェックします。 ファイルが存在すれば true を、そうでなければ nil を返します。 この関数はディレクトリに対しても true を返します。 オプションの bool 値が true の場合、ファイルはディレクトリでなければ str-path-name が返り、ファイルがディレクトリなら nil が返ります。 ファイルの存在は、読み書き許可等の情報を含みませんので、カレント・ユーザによる読み書きの許可を持たない存在かもしれません。
Checks for the existence of a file in str-name. Returns true if the file exists; otherwise, it returns nil. This function will also return true for directories. If the optional bool value is true, the file must not be a directory and str-path-name is returned or nil if the file is a directory. The existence of a file does not imply anything about its read or write permissions for the current user.

(if (file? "afile") (set 'fileNo (open "afile" "read")))

(file? "/usr/local/bin/newlisp" true)  "/usr/local/bin/newlisp"
(file? "/usr/local/bin/foo" true)      nil


filter

syntax: (filter exp-predicate exp-list)

exp-predicate の述部を exp-list のリストの各要素に適用します。 exp-predicatetrue となる要素の入ったリストが返ります。 filter は、述部を否定的に使った clean のように動作します。
The predicate exp-predicate is applied to each element of the list exp-list. A list is returned containing the elements for which exp-predicate is true. filter works like clean, but with a negated predicate.

(filter symbol? '(1 2 d 4 f g 5 h))   (d f g h)

(define (big? x) (> x 5))   (lambda (x) (> x 5))

(filter big? '(1 10 3 6 4 5 11))   (10 6 11)

; filter with comparison functor
(set 'L '((a 10 2 7) (b 5) (a 8 3) (c 8) (a 9)))

(filter (curry match '(a *)) L)    ((a 10 2 7) (a 8 3) (a 9))

(filter (curry match '(? ?)) L)    ((b 5) (c 8) (a 9))

(filter (curry match '(* 8 *)) L)  ((a 8 3) (c 8))

述部は組込述語か、ユーザ定義関数か、ラムダ式です。
The predicate may be a built-in predicate, a user-defined function, or a lambda expression.

別のリストを使ってリストの要素をフィルタリングするのには、(listモードの)関数 difference か、関数intersect を使います。
For filtering a list of elements with the elements from another list, use the difference function or intersect (with the list option).

同様の関数として、フィルタされた要素のインデックスを返す関数 index と述部が偽(訳注:nil)となるリストの要素を全て返す関数 clean も見てください。
See also the related function index, which returns the indices of the filtered elements and clean, which returns all elements of a list for which a predicate is false.



find

syntax: (find exp-key list [func-compare | regex-option])
syntax: (find str-key str-data [regex-option [int-offset]])

Find an expression in a list(リスト中に式を見つける)

第二引数list がリストに評価されると、findexp-key の評価値が得られる要素のインデックス位置(オフセット)を返します。
If the second argument evaluates to a list, then find returns the index position (offset) of the element derived from evaluating exp-key.

オプションで、演算子かユーザ定義関数を func-compare に指定できます。 exp-key が文字列なら、正規表現オプションが regex-option パラメータとして指定できます。
Optionally, an operator or user-defined function can be specified in func-compare. If the exp-key is a string, a regular expression option can be specified with the regex-option parameter.

正規表現か、比較ファンクタ(関数オブジェクト)を使った時は、システム変数 $0 に見つかった最後の要素がセットされます。
When using regular expressions or comparison functors the system variable $0 is set to the last element found.

; find an expression in a list
(find '(1 2) '((1 4) 5 6 (1 2) (8 9)))   3

(find "world" '("hello" "world"))        1
(find "hi" '("hello" "world"))           nil

(find "newlisp" '("Perl" "Python" "newLISP") 1)   2

; use the comparison functor
(find 3 '(8 4 3  7 2 6) >)   4
$0  2

(find "newlisp" '("Perl" "Python" "newLISP") 
                 (fn (x y) (regex x y 1)))  2
$0  "newLISP"

(find 5 '((l 3) (k 5) (a 10) (z 22)) 
         (fn (x y) (= x (last y))))   1
$0  (k 5)

(find '(a ?) '((l 3) (k 5) (a 10) (z 22)) match)   2
$0  (a 10)

(find '(X X) '((a b) (c d) (e e) (f g)) unify)   2
$0  (e e)

; define the comparison functor first for better readability
(define (has-it-as-last x y) (= x (last y)))

(find 22 '((l 3) (k 5) (a 10) (z 22)) has-it-as-last)   3
$0  (z 22)

matchunify を使ったリスト検索は、文字列に対する正規表現のよりパワフルな定型化が可能になります。
Using match and unify, list searches can be formulated which are as powerful as regular expression searches are for strings.

Find a string in a string(文字列中に文字列を見つける)

第二引数 str-data が文字列に評価されると、(第一引数 str-data で最初に見つかった)str-key 文字列のオプセット位置が返ります。 この場合、find はバイナリの str-data にも動作します。 返ってくるオフセット位置は、UTF-8 バージョンの newLISP であっても、常に 1 バイト単位で計数されます。
If the second argument, str-data, evaluates to a string, then the offset position of the string str-key (found in the first argument, str-data) is returned. In this case, find also works on binary str-data. The offset position returned is always based on counting single byte characters even when running the UTF-8 enabled version of newLISP.

第三パラメータの存在は、(例えば、大文字小文字を区別しない 1(一)か、区別する 0(ゼロ)の)regex-option で指定されるオプション番号と共に str-pattern の正規表現パターンを使った検索を指定します。 regex-option が指定されると、文字列の先頭からでなく、与えられたオフセットからの検索を始めるために int-offset 引数も指定可能です。 いずれにせよ、find が返す位置は文字列の先頭から計算されます。
The presence of a third parameter specifies a search using the regular expression pattern specified in str-pattern, as well as an option number specified in regex-option (i.e., 1 (one) for case-insensitive search or 0 (zero) for no special options). If regex-option is specified an optional int-offset argument can be specified too to start the search not at the beginning but at the offset given. In any case the position returned by find is calculated relative to the beginning of the string.

正規表現を用いない単純な文字列検索で int-offset を指定するには、regex-optionnil を指定してください。
To specify int-offset in a simple string search without regular expressions, specify nil for regex-option.

newLISP では、正規表現は標準のPerl互換正規表現 (PCRE) 検索です。 見つかった式や部分式は、システム変数$0, $1, $2等々に入り、他のシンボルのように扱えます。 これらの変数の内容は ($ 0), ($ 1), ($ 2)等々を代わりに使ってもアクセスできます。 この方法は、インデックスを使ったアクセスを許可します(例えば ($ i)、ここで i は整数)。
In newLISP, regular expressions are standard Perl Compatible Regular Expression (PCRE) searches. Found expressions or subexpressions are returned in the system variables $0, $1, $2, etc., which can be used like any other symbol. As an alternative, the contents of these variables can also be accessed by using ($ 0), ($ 1), ($ 2), etc. This method allows indexed access (i.e., ($ i), where i is an integer).

正規表現検索におけるオプション番号の意味や詳しい情報は、regex を見てください。
See regex for the meaning of the option numbers and more information on regular expression searching.

; simple string search
(find "world" "Hello world")   6
(find "WORLD" "Hello woRLd")   nil

; case-insensitive regex

(find "WorlD" "Hello woRLd" 1)   6   
                                
(find "hi" "hello world")        nil
(find "Hello" "Hello world")     0

; regex with default options

(find "cat|dog" "I have a cat" 0)   9 
$0                                  "cat"
(find "cat|dog" "my dog" 0)         3
$0                                  "dog"
(find "cat|dog" "MY DOG" 1)         3
$0                                  "DOG"

; use an optional offset
(find "cat|dog" "I have a cat and a dog" 0)     9
(find "cat|dog" "I have a cat and a dog" 0 12)  19

;; find with subexpressions in regular expression
;; and access with system variables

(set 'str  "http://nuevatec.com:80")

(find "http://(.*):(.*)" str 0)   0
                                 
$0   "http://nuevatec.com:80"
$1   "nuevatec.com"
$2   "80"

;; system variables as an indexed expression (since 8.0.5)
($ 0)   "http://nuevatec.com:80"
($ 1)   "nuevatec.com"
($ 2)   "80"

他に正規表現を使う関数としては、 directoryfind-allparseregexreplacesearch を見てください。
For other functions using regular expressions, see directory, find-all, parse, regex, replace, and search.

入れ子になった式や多次元リストの検索には、refref-all を使ってください。
To find expressions in nested or multidimensional lists, use the ref and ref-all functions.



find-all

syntax: (find-all str-regex-pattern str-text [exp [regex-option]])
syntax: (find-all list-match-pattern list [exp])
syntax: (find-all exp-key list [exp [func-compare]])

第一構文の find-all は、テキストstr-text 中に str-regex-pattern の出現を全て見つけ、一致した全ての文字列のリストを返します。 一致するもが見つからない時は、空リスト () が返ります。 第一構文では、regex-option の指定がなくても、文字列検索は正規表現パターンを使って行われます。 システム変数 $count が検出された一致数で更新されます。
In the first syntax, find-all finds all occurrences of str-regex-pattern in the text str-text, returning a list containing all matching strings. The empty list () is returned if no matches are found. In the first syntax string searches are always done using regular expression patterns, even if no regex-option is specified. The system variable $count is updated with the number of matches found.

オプションで、戻りリストに入る前の見つかった文字列や正規表現部分式を処理する式が指定できます。 追加オプション regex-option は、特殊正規表現のオプションです(詳細は、regex を見てください)。
Optionally, an expression can be specified to process the found string or regular subexpressions before placing them into the returned list. An additional option, regex-option, specifies special regular expression options (see regex for further details).

(find-all {\d+} "lkjhkljh34ghfdhgfd678gfdhfgd9")
 ("34" "678" "9")

$count  3

(find-all {(new)(lisp)} "newLISPisNEWLISP" (append $2 $1) 1)
 ("LISPnew" "LISPNEW")

(unique (sort 
    (find-all {[a-zA-Z]+} 
        (replace "<[^>]+>" (get-url "http://newlisp.org") "" 0) )
))
 ("A" "ACC" "AI" "API" "About" "All" "Amazing" "Apps"
...
"where" "whole" "width" "wiki" "will" "with" "work" "written")

; use $count in evaluated expr
(find-all "a" "ababab" (string $count $it))  ("1a" "2a" "3a")

最初の例は、テキスト中の全ての数字を見つけています。 二番目の例は、正規表現パターン str-pattern で検索された部分式に、オプション式 exp がどのように動作するかを示しています。 最後の例は、ウェブ・ページを取り込み、HTMLタグを消去してから、全ての単語を単一(訳注:重複する単語がない)にして、ソートしたリストに集めています。
The first example discovers all numbers in a text. The second example shows how an optional expression in exp can work on subexpressions found by the regular expression pattern in str-pattern. The last example retrieves a web page, cleans out all HTML tags, and then collects all words into a unique and sorted list.

文字列に対しての find-all は、regex-option がなくても、常に正規表現検索を実行することに注意してください。
Note that find-all with strings always performs a regular expression search, even if the option in regex-option is omitted.

第二構文の find-all は、list 中でパターン list-match-patternmatch する全てのリストを探し出します。 文字列に対しての find-all のように、list で見つかる match した部分リストを処理する式が exp に指定できます。 システム変数 $count は検出された一致数で更新されます。
In the second syntax, find-all searches for all list match patterns list-match-pattern in list. As in find-all for strings, an expression can be specified in exp to process further the matched sublist found in list. The system variable $count is updated with the number of matches found.

(find-all '(? 2) '((a 1) (b 2) (a 2) (c 4)))  ((b 2) (a 2))

(find-all '(? 2) '((a 1) (b 2) (a 2) (c 4)) (first $it))  (b a)

$count  2

リスト合致用の find-all は、部分リスト検索時の比較に match を使い、常にパターン表現のリストを必要とします。
find-all for list matches always uses match to compare when searching for sublists and always needs a list for the pattern expression.

第三構文の find-all では、リスト要素とキーとなる exp-key 式の比較用に、組込かユーザ定義関数が指定できます:
In the third syntax, find-all can specify a built-in or user-defined function used for comparing list elements with the key expression in exp-key:

(find-all 5 '(2 7 4 5 9 2 4 9 7 4 8) $it <)  (7 9 9 7 8)

; process the found element available in $it

(find-all 5 '(2 7 4 5 9 2 4 9 7 4 8) (* 3 $it) <)  (21 27 27 21 24)
; same as
(find-all 5 '(2 7 4 5 9 2 4 9 7 4 8) (* 3 $it) (fn (x y) (< x y)))  (21 27 27 21 24)


(find-all 5 '(2 7 4 5 9 2 4 9 7 4 8) ("abcdefghijk" $it) <)  ("h" "j" "j" "h" "i")

$count  5

; use $count
(find-all 'a '(a b a b a b) (list $count $it))  ((1 a) (2 a) (3 a))

検索する式やリストに含める式は、どんな型も可能です。 この構文の find-allfilter のように動作しますが、 追加の利点として、見つけた要素を処理する式が定義できます。
Any type of expression can be searched for or can be contained in the list. find-all in this syntax works similar to filter but with the added benefit of being able to define a processing expression for the found element.

func-compare が定義されず、exp-key がリストなら、第二構文としての match が比較に使われるでしょう。
If no func-compare is defined and exp-key is a list, then match will be used for comparison, as in the second syntax.



first utf8

syntax: (first list)
syntax: (first array)
syntax: (first str)

リストの最初の要素や文字列の最初の文字を返します。 引数は変わりません。 この関数は、他の Lisp方言の carhead と等価です。
Returns the first element of a list or the first character of a string. The operand is not changed. This function is equivalent to car or head in other Lisp dialects.

(first '(1 2 3 4 5))        1
(first '((a b) c d))        (a b)
(set 'aList '(a b c d e))   (a b c d e)
(first aList)               a
aList                       (a b c d e)
(set 'A (array 3 2 (sequence 1 6)))
  ((1 2) (3 4) (5 6))
(first A)                   (1 2)

(first '())                 ERR: list is empty

第三構文では、文字列 str から、最初の文字が文字列として返ります。
In the third syntax, the first character is returned from the string in str as a string.

(first "newLISP")          "n"
(first (rest "newLISP"))   "e"

UTF-8 版の newLISP を使うと、first はバイト境界ではなく、キャラクタ境界で動作します。 関数 lastrest も見てください。
Note that first works on character boundaries rather than byte boundaries when the UTF-8–enabled version of newLISP is used. See also the functions last and rest.



flat

syntax: (flat list [int-level])

フラットなリストを返します(訳注:入れ子の括弧をなくしたリストになる):
Returns a flattened list from a list:

(set 'lst '(a (b (c d))))
(flat lst)   (a b c d)

(map (fn (x) (ref x lst)) (flat lst))
 ((0) (1 0) (1 1 0) (1 1 1))

オプションのパラメータ int-level は、リストをフラット化する時の入れ子レベルを制限します。
The optional int-level parameter can be used to limit the recursion level when flattening the list:

(flat '(a b (c d (e f)) (g h (i j))) )    (a b c d e f g h i j)

(flat '(a b (c d (e f)) (g h (i j))) 1)   (a b c d (e f) g h (i j))

(flat '(a b (c d (e f)) (g h (i j))) 2)   (a b c d e f g h i j)

int-level0 の時、フラット化は行われません。
If int-level is 0, no flattening will occur.

flat を使えば、入れ子リストでも繰り返しに使えるようになります。
flat can be used to iterate through nested lists.



float

syntax: (float exp [exp-default])

exp の式が数値か文字列に評価されたなら、引数が浮動小数点数に変換され、返されます。 exp が浮動小数点数に変換できないなら、 nil か、指定された exp-default の評価が返されます。 この関数は、主にユーザ入力やテキストの読み取り・解析時の文字列の変換に使われます。 文字列は、数値か +(プラス記号)か -(マイナス記号)か .(ピリオド)で始まっている必要があります。 exp が無効なら、float はデフォルト値として nil を返します。
If the expression in exp evaluates to a number or a string, the argument is converted to a float and returned. If exp cannot be converted to a float then nil or, if specified, the evaluation of exp-default will be returned. This function is mostly used to convert strings from user input or when reading and parsing text. The string must start with a digit or the + (plus sign), - (minus sign), or . (period). If exp is invalid, float returns nil as a default value.

指数項が 1e308 より大きいか、-1e308 より小さい浮動小数点数は、それぞれ +INF か -INF に変換されます。 +INF と -INF の表示は、プラットフォームやコンパイラによって異なります。
Floats with exponents larger than 1e308 or smaller than -1e308 are converted to +INF or -INF, respectively. The display of +INF and -INF differs on different platforms and compilers.

(float "1.23")        1.23
(float " 1.23")       1.23
(float ".5")          0.50
(float "-1.23")       -1.23
(float "-.5")         nil
(float "#1.23")       nil
(float "#1.23" 0.0)   0

(float? 123)           nil
(float? (float 123))   true

(float '(a b c))     nil
(float '(a b c) 0)   0
(float nil 0)        0

(float "abc" "not a number")   "not a number"
(float "1e500")                inf
(float "-1e500")               -inf

(print "Enter a float num:")
(set 'f-num (float (read-line)))

整数値の構文解析には、関数 int を使ってください。
Use the int function to parse integer numbers.



float?

syntax: (float? exp)

exp が浮動小数点数に評価される時のみ true が、そうでない時に nil が返ります。
true is returned only if exp evaluates to a floating point number; otherwise, nil is returned.

(set 'num 1.23)
(float? num)   true
(訳例:
> (sqrt -1)
nan
> (float? (sqrt -1))
true
> (div 1 0)
inf
> (float? (div 1 0))
true
 NaNINF の型は、浮動小数点数です。)


floor

syntax: (floor number)

浮動小数点数の number より、次に小さい整数値が返ります。
Returns the next lowest integer below number as a floating point.

(floor -1.5)   -2
(floor 3.4)    3

関数 ceil も見てください。
See also the ceil function.



flt

syntax: (flt number)

number を32ビット浮動小数点数の整数表現に変換します。 この関数は、ライブラリ・ルーチンへ 32 ビット浮動小数点数を渡す時に使われます。 newLISP の浮動小数点数は 64 ビットで、導入した C ライブラリ・ルーチンを呼び出す時は、64ビット浮動小数点数が渡されます。
Converts number to a 32-bit float represented by an integer. This function is used when passing 32-bit floats to library routines. newLISP floating point numbers are 64-bit and are passed as 64-bit floats when calling imported C library routines.

(flt 1.23)   1067282596

;; pass 32-bit float to C-function: foo(float value) 
(import "mylib.so" "foo")
(foo (flt 1.23))

(get-int (pack "f" 1.23))   1067282596

(unpack "f" (pack "ld" (flt 1.2345)))   (1.234500051)

最後の二つの動作は、flt の内部動作を示しています。
The last two statements illustrate the inner workings of flt.

ライブラリの導入には、関数 import を使ってください。
Use the import function to import libraries.



fn

syntax: (fn (list-parameters) exp-body)

fnlambda は無名関数の定義に使われ、関数を引数とする mapsort等の多くの関数でよく使われます。 fnlambda はそれ自体のシンボルは存在しませんが、特殊リスト型:ラムダ・リスト を指定します。 fn-macrolambda-macro と共に、これらの用語はソース解析で認識され、リストの特殊型を指定しますので、関数や演算子のように使うことができます。
fn or lambda are used to define anonymous functions, which are frequently used in map, sort, and all other expressions where functions can be used as arguments. The fn or lambda word does not exist on its own as a symbol, but indicates a special list type: the lambda list. Together with fn-macro and lambda-macro these terms are recognized during source parsing. They indicate a specialized type of list which can be used and applied like a function or operator.

無名関数を使えば、define を使う新しい関数の定義を省けます。 その代わりに、関数が直接定義されるのです:
Using an anonymous function eliminates the need to define a new function with define. Instead, a function is defined on the fly:

(map (fn (x) (+ x x)) '(1 2 3 4 5))  (2 4 6 8 10)

(sort '(".." "..." "." ".....") (fn (x y) (> (length x) (length y))))
 ("....." "..." ".." ".")

例では、整数 (x) を取って二倍にする関数 fn(x) を定義しています。 この関数は、map を使って、引数のリストに展開されます 。 二番目の例は、長さでソートされる文字列を示しています。
The example defines the function fn(x), which takes an integer (x) and doubles it. The function is mapped onto a list of arguments using map. The second example shows strings being sorted by length.

(長い間、伝統的形式であった) 関数 lambda は、fn に置き換えることができます。
The lambda function (the longer, traditional form of writing) can be used in place of fn.



for

syntax: (for (sym num-from num-to [num-step [exp-break]]) body)

num-fromnum-to により指定される範囲(num-fromnum-toを含む)で、body の式群を繰り返し評価します。 刻み幅は num-step に指定できます。 刻み幅が指定されなければ、1 になります。 (訳注:刻み幅の有無で sym の型が変わります。詳細は下に記述あり。)
Repeatedly evaluates the expressions in body for a range of values specified in num-from and num-to, inclusive. A step size may be specified with num-step. If no step size is specified, 1 is assumed.

オプションで、exp-break に早期脱出条件を定義できます。 中断式が nil 以外に評価されると、for ループは exp-break の値を返します。 中断条件は body を評価する前にテストされます。 中断条件を定義する際は、num-step も定義しなければなりません。
Optionally, a condition for early loop exit may be defined in exp-break. If the break expression evaluates to any non-nil value, the for loop returns with the value of exp-break. The break condition is tested before evaluating body. If a break condition is defined, num-step must be defined, too.

for 式にとって、シンボル sym はダイナミック・スコープのローカル変数で、刻み幅が指定されない時は整数となり、刻み幅がある時は浮動小数点数となって指定された範囲内の各値を連続して取ります。 for 宣言文の評価が終わった後、sym は以前の値になります。 (訳注:15.ダイナミック スコープとレキシカル スコープの章を参照してください。)
The symbol sym is local in dynamic scope to the for expression. It takes on each value successively in the specified range as an integer value if no step size is specified, or as a floating point value when a step size is present. After evaluation of the for statement sym assumes its previous value.

> (for (x 1 10 2) (println x))
1
3
5
7
9

> (for (x 8 6 0.5) (println x))
8
7.5
7
6.5
6

> (for (x 1 100 2 (> (* x x) 30)) (println x))
1
3
5
true
> _

二番目の例は、大きい方から小さい方への数の範囲を使っています。 刻み幅は、常に正の数値であることに注意してください。 三番目の例では、中断条件がテストされています。
The second example uses a range of numbers from highest to lowest. Note that the step size is always a positive number. In the third example, a break condition is tested.

連続した数値の生成には、関数 sequence を使ってください。
Use the sequence function to make a sequence of numbers.



for-all

syntax: (for-all func-condition list)

list の全要素に func-condition の関数を適用します。 全要素が func-condition の条件に一致したなら、結果は true になり、そうでなければ nil が返ります。
Applies the function in func-condition to all elements in list. If all elements meet the condition in func-condition, the result is true; otherwise, nil is returned.

(for-all number? '(2 3 4 6 7))                  true

(for-all number? '(2 3 4 6 "hello" 7))          nil

(for-all (fn (x) (= x 10)) '(10 10 10 10 10))   true

リスト中の少なくとも一個が条件に合っているかどうかをチェックするには、関数 exists を使ってください。
Use the exists function to check if at least one element in a list meets a condition.



fork

syntax: (fork exp)

exp の式がプラットフォーム OS の newLISP の子プロセス・スレッドとして、起動されます。 この新プロセスは全てのアドレス空間を継承しますが独立して走り、子プロセスで変化するシンボルや変数の内容は親プロセスに影響しませんし、その逆もしかりです。 子プロセスは exp の評価が終了した時点で終わります。
The expression in exp is launched as a newLISP child process-thread of the platforms OS. The new process inherits the entire address space, but runs independently so symbol or variable contents changed in the child process will not affect the parent process or vice versa. The child process ends when the evaluation of exp finishes.

fork は成功すると子プロセスID を返し、失敗すると nil を返します。 子プロセスの終了を待つ関数 wait-pid も見てください。
On success, fork returns with the child process ID; on failure, nil is returned. See also the wait-pid function, which waits for a child process to finish.

この関数は Linux/Unix 版の newLISP で利用可能で、基盤となる OS に実装されている fork() をベースにしています。
This function is only available on Linux/Unix versions of newLISP and is based on the fork() implementation of the underlying OS.

プロセスの起動や結果の収集をより簡単に自動化する方法として、spawnCilk API が利用可能です。
A much simpler automated method to launch processes and collect results is available with spawn and the Cilk API.

> (set 'x 0)
0
> (fork (while (< x 20) (println (inc x)) (sleep 1000)))
176

> 1
2
3
4
5
6

この例が示しているのは、子プロセス・スレッドがシンボル空間を継承している様子や、親プロセスと独立している様子です。 fork 宣言文は、すぐにプロセス ID 176 を返します。 子プロセスは、変数 x を一秒毎に一ずつ加算して標準出力に出力します(太字)。 親プロセスは、コマンド受付可能です。 親プロセスで、シンボル x がまだ値 0 (zero) を保持していることを確かめるたに、x とタイプして見てください。 子プロセスの出力と混在した状態で宣言文を入力することになりますが、親プロセスには正しく入力されます。
The example illustrates how the child process-thread inherits the symbol space and how it is independent of the parent process. The fork statement returns immediately with the process ID 176. The child process increments the variable x by one each second and prints it to standard out (boldface). In the parent process, commands can still be entered. Type x to see that the symbol x still has the value 0 (zero) in the parent process. Although statements entered will mix with the display of the child process output, they will be correctly input to the parent process.

次の例は、プロセス間の通信に pipe が使われる様子を示しています。
The second example illustrates how pipe can be used to communicate between processes.

#!/usr/local/bin/newlisp

(define (count-down-proc x channel)
  (while (!= x 0)
      (write-line channel (string x))
      (dec x)))

(define (observer-proc channel)
  (do-until (= i "1")
    (println "process " (setq i (read-line channel)))))

(map set '(in out) (pipe))
(set 'observer (fork (observer-proc in)))
(set 'counter (fork (count-down-proc 5 out)))

; avoid zombies
(wait-pid observer)
(wait-pid counter)

(exit)

次のような出力が observer-proc によって生成されます。
The following output is generated by observer-proc

process 5
process 4
process 3
process 2
process 1

count-down-proc は通信パイプに数を書き込み、それらは observer-process で拾われ、出力されます。
The count-down-proc writes numbers to the communication pipe, where they are picked up by the observer-process and displayed.

分岐したプロセスはそれ自身で終了することも、関数 destroy を使って破棄することもできます。
A forked process can either exit by itself or it can be destroyed using the destroy function.

(define (fork-destroy-demo)
    (set 'pid (fork (dotimes (i 1000) (println i) (sleep 10))))
    (sleep 50)
    (destroy pid) 
)

> (fork-destroy-demo)
0
1
2
3
4
true
> 

fork-destroy-demo で開始されたプロセスは終了しませんが、開始 50 ミリ秒後に destroy が呼び出されて破棄されます。
The process started by fork-destroy-demo will not finish but is destroyed 50 milli-seconds after start by a call to destroy.

プロセスの同期には関数 semaphore を、プロセス間のメモリの共有には share を使ってください。
Use the semaphore function for synchronizing processes and share for sharing memory between processes.

プロセスの同期や結果の収集をより簡単に、かつ自動化する spawn を見てください。
See spawn for a much simpler and automated way to synchronize processes and collect results.



format

syntax: (format str-format exp-data-1 [exp-data-2 ... ])
syntax: (format str-format list-data)

str-format の評価で指定されるフォーマットを使って、exp-data-1 の整形した文字列を作成します。 指定する形式は ANSI C言語の関数 printf() で使われるフォーマットと同じです。 str-format に一個より多いフォーマット指定子を指定することで、二つ以上の引数 exp-data を取れます。
Constructs a formatted string from exp-data-1 using the format specified in the evaluation of str-format. The format specified is identical to the format used for the printf() function in the ANSI C language. Two or more exp-data arguments can be specified for more than one format specifier in str-format.

もう一つの構文では、整形されるデータは list-data のリストの中から渡されます。
In an alternative syntax, the data to be formatted can be passed inside a list in list-data.

format は、フォーマット文字列の有効性、データ型の一致、引数の数が合っているかをチェックします。 間違ったフォーマットやデータ型には、エラー・メッセージが返ります。 intfloatstring を使えば、適正なデータ型が保証され、エラー・メッセージが回避されます。
format checks for a valid format string, matching data type, and the correct number of arguments. Wrong formats or data types result in error messages. int, float, or string can be used to ensure correct data types and to avoid error messages.

フォーマット文字列は次のような一般形式を持ちます:
The format string has the following general format:

"%w.pf"

%(パーセント記号)でフォーマット指定が開始されます。 フォーマット文字列内で % を表したい時は二度書きします:%%
The % (percent sign) starts a format specification. To display a % inside a format string, double it: %%

Linux では、パーセント記号の後にシングル・クォート %' を続けて、数値形式に千単位の区切りを入れることができます。
On Linux the percent sign can be followed by a single quote %' to insert thousand's separators in number formats.

w は幅フィールドです。 データは、右詰めですが、- (マイナス符号) が先に付くと左詰めになります。 + (プラス符号) が付くと、正の数字は +(訳注:負の数字は - )付きで表示されます。 先にゼロが付くと、使われないスペースがゼロで埋められます。 幅フィールドはオプションで、全データ型に提供されます。
The w represents the width field. Data is right-aligned, except when preceded by a minus sign, in which case it is left-aligned. If preceded by a + (plus sign), positive numbers are displayed with a +. When preceded by a 0 (zero), the unused space is filled with leading zeroes. The width field is optional and serves all data types.

p は(浮動小数点専用の)十進数桁数か文字列の桁数で、ピリオドで幅フィールドから切り分けられます。 桁数はオプションです。 文字列に桁フィールドを使うと、表示される文字数が p で制限されます。
The p represents the precision number of decimals (floating point only) or strings and is separated from the width field by a period. Precision is optional. When using the precision field on strings, the number of characters displayed is limited to the number in p.

f は型フラグで必須項目です。つまり、省略できません。
The f represents a type flag and is essential; it cannot be omitted.

f には下記の型があります:
Below are the types in f:

形式
format
内容
description
s文字列
text string
c一文字( 1 から 255 までの値)
character (value 1 - 255)
d十進数(32ビット)
decimal (32-bit)
u符号なし十進数(32ビット)
unsigned decimal (32-bit)
x小文字による十六進数
hexadecimal lowercase
X大文字による十六進数
hexadecimal uppercase
o八進数(32ビット)
octal (32-bits) (not supported on all of newLISP flavors)
f実数
floating point
e小文字による指数
scientific floating point
E大文字による指数
scientific floating point
g汎用的実数(訳注:数値の応じて fe
general floating point
G汎用的実数(訳注:数値の応じて fE
general floating point

32 ビット・フォーマット指定子を使って 64 ビット数値を定型化すると、切り詰められて64 ビット・システムでは下位 32 ビット数字に整形されます。32ビット・システムではオーバーフローして 0xFFFFFFFF になります。
Formatting 64-bit numbers using the 32-bit format specifiers from above table will truncate and format the lower 32 bits of the number on 64-bit systerms and overflow to 0xFFFFFFFF on 32-bit systems.

32 ビット数値及び 64 ビット数値には、下記のフォーマット文字列を使ってください。32 ビットのプラットフォームでは、64 ビット数値は32 ビットに切り詰められます:
For 32-bit and 64-bit numbers use the following format strings. 64-bit numbers will be truncated to 32-bit on 32-bit platforms:

formatdescription
lddecimal (32/64-bit)
luunsigned decimal (32/64-bit)
lxhexadecimal (32/64-bit)
lXhexadecimal uppercase (32/64-bit)

Unixライクのオペレーティング・システムや MS Windows では、64ビット数値に下記のフォーマット文字列を使ってください(TRU64 ではサポートされません):
For 64-bit numbers use the following format strings on Unix-like operating systems and on MS Windows (not supported on TRU64):

formatdescription
llddecimal (64-bit)
lluunsigned decimal (64-bit)
llxhexadecimal (64-bit)
llXhexadecimal uppercase(64-bit)

MS Windows プラットフォームでのみ、64ビット数値に下記の文字列を使ってください:
On Windows platforms only the following characters apply for 64 bit numbers:

formatdescription
I64ddecimal (64-bit)
I64uunsigned decimal (64-bit)
I64xhexadecimal (64-bit)
I64Xhexadecimal uppercase(64-bit)

他のテキストは、フォーマット指定子間かフォーマット指定子の前後に置けます。
Other text may occur between, before, or after the format specs.

Tru64 Unix では、フォーマット文字 id の代わりに使えることを記しておきます。
Note that on Tru64 Unix the format character i can be used instead of d.



(format ">>>%6.2f<<<" 1.2345)      ">>>  1.23<<<"
(format ">>>%-6.2f<<<" 1.2345)     ">>>1.23  <<<"
(format ">>>%+6.2f<<<" 1.2345)     ">>> +1.23<<<"
(format ">>>%+6.2f<<<" -1.2345)    ">>> -1.23<<<"
(format ">>>%-+6.2f<<<" -1.2345)   ">>>-1.23 <<<"

(format "%e" 123456789)         "1.234568e+08"
(format "%12.10E" 123456789)    "1.2345678900E+08"

(format "%10g" 1.23)    "      1.23"
(format "%10g" 1.234)   "     1.234"

(format "Result = %05d" 2)   "Result = 00002"

(format "%14.2f" 12345678.12)    "   12345678.12"
; on UNIX glibc compatible platforms only (Linux, macOS 10.9) on some locales
(format "%'14.2f" 12345678.12)  " 12,345,678.12"

(format "%8d" 12345)    "   12345"
; on UNIX glibc compatible platforms only (Linux, macOS 10.9) on some locales
(format "%'8d" 12345)   "  12,345"

(format "%-15s" "hello")         "hello          "
(format "%15s %d" "hello" 123)   "          hello 123"
(format "%5.2s" "hello")         "   he"
(format "%-5.2s" "hello")        "he   "

(format "%o" 80)     "120"
                                
(format "%x %X" -1 -1)   "ffffffff FFFFFFFF"

; 64 bit numbers on Windows
(format "%I64X" 123456789012345678)   "1B69B4BA630F34E"

; 64 bit numbers on Unix (except TRU64)
(format "%llX" 123456789012345678)    "1B69B4BA630F34E"
                                
(format "%c" 65)   "A"

整形するデータは、リストでも渡せます:
The data to be formatted can be passed inside a list:

(set 'L '("hello" 123))
(format "%15s %d" L)   "          hello 123"

newLISP の format は、フォーマット文字列が要求すれば、自動的に浮動小数点から整数、または、整数から浮動小数点への変換を行います:
If the format string requires it, newLISP's format will automatically convert integers into floating points or floating points into integers:

(format "%f" 123)       123.000000
                       
(format "%d" 123.456)   123


fv

syntax: (fv num-rate num-nper num-pmt num-pv [int-type])

開始の元金 num-pv を固定支払い金額 num-pmt と固定利率 num-ratenum-nper 回支払った後のローン残高を計算します。支払いが期間の終わりなら int-type0(ゼロ)にするか省略し、支払いが期間の始めなら int-type を 1 にします(訳注:期間の終わりなら残金に固定利率がかかった後での支払い、逆に期間の始めなら支払った後の残金に固定利率がかかる)。
Calculates the future value of a loan with constant payment num-pmt and constant interest rate num-rate after num-nper period of time and a beginning principal value of num-pv. If payment is at the end of the period, int-type is 0 (zero) or int-type is omitted; for payment at the beginning of each period, int-type is 1.

(fv (div 0.07 12) 240 775.30 -100000)   -0.5544645052

例では、100,000 ドルのローンが年率7%で240月後に支払いが終了し、0.55ドル余ることを示しています。(訳注:毎月775.3ドルの支払った場合の計算。ちなみに、int-type が 1 なら、237月後に支払い終了で、3.28ドルの余りです。返済はお早めに!)
The example illustrates how a loan of $100,000 is paid down to a residual of $0.55 after 240 monthly payments at a yearly interest rate of 7 percent.

関数 irrnpernpvpmtpv も見てください。
See also the functions irr, nper, npv, pmt, and pv.



gammai

syntax: (gammai num-a num-b)

num-anum-b で各々指定される値 ab の不完全ガンマ関数を計算します。(訳注:第1種不完全ガンマ関数lower incomplete gamma function)です。)
Calculates the incomplete Gamma function of values a and b in num-a and num-b, respectively.

(gammai 4 5)   0.7349740847

与えられた自由度 df を超えるカイ二乗の確率を得るために不完全ガンマ関数を使うには、次のようにします:
The incomplete Gamma function is used to derive the probability of Chi² to exceed a given value for a degree of freedom, df, as follows:

Q(Chi²|df) = Q(df/2, Chi²/2) = gammai(df/2, Chi²/2)

関数 prob-chi2 も見てください。
See also the prob-chi2 function.



gammaln

syntax: (gammaln num-x)

num-x の値 xガンマ関数の対数を計算します。
Calculates the log Gamma function of the value x in num-x.

(exp (gammaln 6))   120

例では、n! = gamma(n + 1) であることを使って 5 の階乗値を計算しています。
The example uses the equality of n! = gamma(n + 1) to calculate the factorial value of 5.

対数ガンマ関数は、そこから導出されるベータ関数とも関係しています:
The log Gamma function is also related to the Beta function, which can be derived from it:

Beta(z,w) = Exp(Gammaln(z) + Gammaln(w) - Gammaln(z+w))


gcd  bigint

syntax: (gcd int-1 [int-2 ... ])

整数のグループの最大公約数を計算します。 両方共ゼロでない二つの整数の最大公約数は、両方の数値を割りきれる最大整数値です。 gcd は、 int-i 中の最初の二つの整数値の最大公約数を計算し、その結果の最大公約数とパラメータ・リストの次の引数との最大公約数を計算していきます。
Calculates the greatest common divisor of a group of integers. The greatest common divisor of two integers that are not both zero is the largest integer that divides both numbers. gcd will calculate the greatest common divisor for the first two integers in int-i and then further reduce the argument list by calculating the greatest common divisor of the result and the next argument in the parameter list.

(gcd 0)         0
(gcd 0 0)       0
(gcd 10)        10
(gcd 12 36)     12
(gcd 15 36 6)   3 

数学における gcd数の詳細と理論は、Wikipediaを見てください。(訳注:日本語版は、こちらです。
See Wikipedia for details and theory about gcd numbers in mathematics.



get-char 

syntax: (get-char int-address)

int-address で指定されたアドレスから 8 ビット文字を取り出します。 この関数は、import で導入した共有ライブラリ関数を使う時に役立ちます。
Gets an 8-bit character from an address specified in int-address. This function is useful when using imported shared library functions with import.

char * foo(void)
{
char * result;
result = "ABCDEFG";
return(result);
}

キャラクタのポインタ(文字列のアドレス)を返す共有ライブラリの上記 C 関数で考えてみましょう。
Consider the above C function from a shared library, which returns a character pointer (address to a string).

(import "mylib.so" "foo")
(print (get-char (foo) ))         65 ; ASCII "A"
(print (get-char (+ (foo) 1)))    66 ; ASCII "B"

int-address に間違ったアドレスを指定して、関数 get-char を使うことは安全でありませんので注意してください。 そうした場合、結果としてシステムがクラッシュしたり、不安定になったりします。
Note that it is unsafe to use the get-char function with an incorrect address in int-address. Doing so could result in the system crashing or becoming unstable.

関数addressget-intget-longget-floatget-stringpackunpack も見てください。
See also the address, get-int, get-long, get-float, get-string, pack, and unpack functions.



get-float 

syntax: (get-float int-address)

int-address で指定されたアドレスから、64ビット倍精度浮動小数点数を取り出します。 この関数は、(importを使って) 導入した倍精度浮動小数点数のアドレス・ポインタか、倍精度浮動小数点数を含む構造体のポインタを返す共有ライブラリ関数を使う時の助けになります。
Gets a 64-bit double float from an address specified in int-address. This function is helpful when using imported shared library functions (with import) that return an address pointer to a double float or a pointer to a structure containing double floats.

double float * foo(void)
{
double float * result;
…
*result = 123.456;
return(result);
}

前もって C 関数をコンパイルして、共有ライブラリに置きます。
The previous C function is compiled into a shared library.

(import "mylib.so" "foo")
(get-float (foo))   123.456

foo が導入されて呼び出されると、倍精度浮動小数点数のポインタを返します。 int-addressに間違ったアドレスを指定して関数get-float を使うことは安全でなく、そうした場合、結果としてシステムがクラッシュしたり、不安定になったりしますので注意してください。
foo is imported and returns a pointer to a double float when called. Note that get-float is unsafe when used with an incorrect address in int-address and may result in the system crashing or becoming unstable.

関数addressget-intget-longget-charget-stringpackunpack も見てください。
See also the address, get-int, get-long, get-char, get-string, pack, and unpack functions.



get-int 

syntax: (get-int int-address)

int-address で指定されたアドレスから 32ビット整数値を取り出します。 この関数は、整数値のアドレス・ポインタか整数値を含む構造体のポインタを返す、import で導入した共有ライブラリ関数を使う時に便利です。
Gets a 32-bit integer from the address specified in int-address. This function is handy when using imported shared library functions with import, a function returning an address pointer to an integer, or a pointer to a structure containing integers.

int * foo(void)
{
int * result;
…
*result = 123;
return(result);
}

int foo-b(void)
{
int result;
…
result = 456;
return(result);
}

整数ポインタ(整数のアドレス)を返す(共有ライブラリからの) C 関数 foo で考えてみましょう。
Consider the C function foo (from a shared library), which returns an integer pointer (address of an integer).

(import "mylib.so" "foo")
(get-int (foo))   123
(foo-b)           456

int-address に間違ったアドレスを指定して get-int を使うことは、安全でなく、結果としてシステムがクラッシュしたり、不安定になったりしますので、注意してください。
Note that using get-int with an incorrect address in int-address is unsafe and could result in the system crashing or becoming unstable.

関数addressget-charget-floatget-longget-stringpackunpack も見てください。
See also the address, get-char, get-float, get-long, get-string, pack, and unpack functions.



get-long 

syntax: (get-long int-address)

int-address で指定されたアドレスから 64 ビット整数値を取り出します。 この関数は、整数値のアドレス・ポインタか整数値を含む構造体のポインタを返す、import で導入した共有ライブラリ関数を使う時に便利です。
Gets a 64-bit integer from the address specified in int-address. This function is handy when using import to import shared library functions, a function returning an address pointer to a long integer, or a pointer to a structure containing long integers.

long long int * foo(void)
{
int * result;
…
*result = 123;
return(result);
}

long long int foo-b(void)
{
int result;
…
result = 456;
return(result);
}

整数ポインタ(整数のアドレス)を返す(共有ライブラリの)C 関数 foo で考えてみます。
Consider the C function foo (from a shared library), which returns an integer pointer (address of an integer).

(import "mylib.so" "foo")
(get-int (foo))   123
(foo-b)           456

int-address に間違ったアドレスを指定して get-long を使うことは安全でなく、結果としてシステムがクラッシュしたり、不安定になったりしますので、注意してください。
Note that using get-long with an incorrect address in int-address is unsafe and could result in the system crashing or becoming unstable.

関数addressget-charget-floatget-intget-stringpackunpack も見てください。
See also the address, get-char, get-float, get-int, get-string, pack, and unpack functions.



get-string 

syntax: (get-string int-address [int-bytes [str-limit])

int-address で指定されたアドレスから文字列を取り出します。 この関数は、importで導入した共有ライブラリ関数を使う時の助けになります。
Gets a character string from the address specified in int-address. This function is helpful when using imported shared library functions with import.

char * foo(void)
{
char * result;
result = "ABCDEFG";
return(result);
}

文字ポインタ(文字列のアドレス)を返す共有ライブラリの上記 C 関数で考えてみます。
Consider the above C function from a shared library, which returns a character pointer (address to a string).

(import "mylib.so" "foo")
(print (get-string (foo)))   "ABCDEFG"

引数に文字列が渡されると、get-string はその引数のアドレスを取ります。 get-string は、最初に \000 (null文字) と会った時、常に終了するので、バッファから文字列を取り出すのに使われます:
When a string is passed as an argument, get-string will take its address as the argument. Because get-string always breaks off at the first first \000 (null character) it encounters, it can be used to retrieve a string from a buffer:

(set 'buff "ABC\000\000\000DEF")   "ABC\000\000\000DEF"

(length buff)   9

(get-string buff)   "ABC"

(length (get-string buff))   3

; get a string from offset into a buffer
(get-string (+ (address buff) 6))  "DEF"

; use unpack to get the whole buffer
(unpack "s9" buff)   ("ABC\000\000\000DEF")

関数get-charget-intget-floatpackunpack も見てください。
See also the get-char, get-int, get-float, pack, and unpack functions.

get-string は、間違ったアドレスを指定されるとシステムがクラッシュしたり、不安定になったりしますので、注意してください。
Note that get-string can crash the system or make it unstable if the wrong address is specified.



get-url

syntax: (get-url str-url [str-option] [int-timeout [str-header]])

str-url の URL で指定されたウェブ・ページかファイルを、HTTP プロトコルを使って読み込みます。 http://file:// のどちらの URL も処理されます。 "header" は、ヘッダーだけを取り出すために str-option の引数オプションを指定可能です。 "list" オプションは、ヘッダーとページ情報を分離して文字列リストにして返し、リストの第三項目にはサーバー・ステータス・コードも含まれています(10.6.4 以降)。 オプション "raw"(10.6.4 以降)は、単独でも他のオプションと一緒にでも使用でき、ヘッダー・ロケーション・リダイレクトを抑制します。
Reads a web page or file specified by the URL in str-url using the HTTP GET protocol. Both http:// and file:// URLs are handled. "header" can be specified in the optional argument str-option to retrieve only the header. The option "list" causes header and page information to be returned as separate strings in a list and also includes the server status code as the third list member (since 10.6.4). The "raw" option (since 10.6.4), which can be used alone or combined with other options, suppresses header location redirection.

"debug"オプションは、単独あるいは "header""list" の後に一文字開けて指定します。 例えば、"header debug""list debug" という具合です。 "debug" を含めると、全ての送信情報がコンソール・ウィンドウに出力されます。
A "debug" option can be specified either alone or after the "header" or "list" option separated by one character, i.e. "header debug" or "list debug". Including "debug" outputs all outgoing information to the console window.

引数オプション int-timeout にはミリ秒値を指定できます。 指定時間までにホストからデータを取得できない場合、get-url は文字列 ERR: timeout を返します。 他のエラーが発生した時、get-urlERR: で始まる文字列とエラーの説明を返します。
The optional argument int-timeout can specify a value in milliseconds. If no data is available from the host after the specified timeout, get-url returns the string ERR: timeout. When other error conditions occur, get-url returns a string starting with ERR: and the description of the error.

get-url が受信したヘッダーに Location: 指定子を検出したなら、リダイレクトを処理し、自動的に第二要求リクエストします。 get-urlTransfer-Encoding: chunked フォーマットも理解し、データの厚切りchunkedフォーマットをアンパックします。(訳注:Transfer-Encoding: chunked については、こちらを参照
get-url handles redirection if it detects a Location: spec in the received header and automatically does a second request. get-url also understands the Transfer-Encoding: chunked format and will unpack data into an unchunked format.

newLISP サーバーも get-url要求リクエストを受け付けます。
get-url requests are also understood by newLISP server nodes.

(get-url "http://www.nuevatec.com")
(get-url "http://www.nuevatec.com" 3000)
(get-url "http://www.nuevatec.com" "header")
(get-url "http://www.nuevatec.com" "header" 5000)
(get-url "http://www.nuevatec.com" "list")

(get-url "file:///home/db/data.txt") ; access local file system

(env "HTTP_PROXY" "http://ourproxy:8080")
(get-url "http://www.nuevatec.com/newlisp/")

str-url で指定されたサイトの表示ページは、文字列で返されます。 三行目は、HTTPヘッダーのみが文字列で返されます。 二行目と四行目では、タイム・アウト値が使われています。
The index page from the site specified in str-url is returned as a string. In the third line, only the HTTP header is returned in a string. Lines 2 and 4 show a timeout value being used.

二番目の例は、ローカル・ファイル・システムの /home/db/data.txt をアクセスするために file:// URL を使う方法を示しています。
The second example shows usage of a file:// URL to access /home/db/data.txt on the local file system.

三番目の例は、プロキシ・サーバーの使用例です。 プロキシ・サーバーの URL は、オペレーティング・システム環境変数内になければなりません。 そうするためには、例が示すように関数 env を使って追加できます。
The third example illustrates the use of a proxy server. The proxy server's URL must be in the operating system's environment. As shown in the example, this can be added using the env function.

int-timeout には、str-header オプションのカスタム・ヘッダーを続けることができます。
The int-timeout can be followed by an optional custom header in str-header:

Custom header(カスタム・ヘッダー)

カスタム・ヘッダーには、ブラウザ・クッキーや他のサーバーへ指示がオプションとして入ります。 str-header が指定されない時、newLISP はデフォルトでヘッダー情報を送信します。 次の要求リクエストの後に:
The custom header may contain options for browser cookies or other directives to the server. When no str-header is specified, newLISP sends certain header information by default. After the following request:

(get-url "http://somehost.com" 5000)

newLISP は、以下の要求リクエストとヘッダーを構成して送ります:
newLISP will configure and send the request and header below:

GET / HTTP/1.1        
Host: somehost.com
User-Agent: newLISP v10603
Connection: close

他の選択肢として、str-header オプションを使えます:
As an alternative, the str-header option could be used:

(get-url "http://somehost.com" 5000 
"User-Agent: Mozilla/4.0\r\nCookie: name=fred\r\n")

これにより、newLISP は次の要求リクエストとヘッダーを送信します:
newLISP will now send the following request and header:

GET / HTTP/1.1        
Host: somehost.com
User-Agent: Mozilla/4.o
Cookie: name=fred
Connection: close

カスタム・ヘッダーを使った時の newLISP は、Host:Connection: のヘッダー・エントリーと共に GET 要求リクエストのみを提供することに注意してください。 newLISP は、Host:Connection: エントリーの間にカスタム・ヘッダーで指定された他のエントリーを挿入します。 各エントリーは、改行・復帰ペア: \r\n で終わる必要があります。
Note that when using a custom header, newLISP will only supply the GET request line, as well as the Host: and Connection: header entries. newLISP inserts all other entries supplied in the custom header between the Host: and Connection: entries. Each entry must end with a carriage return line-feed pair: \r\n.

有効なヘッダー・エントリーは、HTTP 処理のリファレンスを見てください。
See an HTTP transactions reference for valid header entries.

カスタム・ヘッダーは、関数put-urlpost-url でも使えます。
Custom headers can also be used in the put-url and post-url functions.



global

syntax: (global sym-1 [sym-2 ... ])

sym-1 [sym-2 ... ] の一つ以上のシンボルが MAIN とは別のコンテキストで普通にアクセスできるようにします。 この宣言文は、MAIN コンテキスト上で実行されなければなりません。 それに、MAIN に所属しているシンボルのみが global 化されます。 global は、最後に global 化されたシンボルを返します。
One or more symbols in sym-1 [sym-2 ... ] can be made globally accessible from contexts other than MAIN. The statement has to be executed in the MAIN context, and only symbols belonging to MAIN can be made global. global returns the last symbol made global.

(global 'aVar 'x 'y 'z)   z

(define (foo x) 
(…))

(constant (global 'foo))

二番目の例は、先に定義した関数を global 化して保護するために、一つの宣言文で constantglobal を使う方法を示しています。
The second example shows how constant and global can be combined into one statement, protecting and making a previous function definition global.



global?

syntax: (global? sym)

sym が global かどうかをチェックします。 組込関数群、コンテキスト・シンボル群、global を使って global 化されたシンボル群が global です:
Checks if symbol in sym is global. Built-in functions, context symbols, and all symbols made global using the function global are global:

global? 'print)    true
(global 'var)      var
(global? 'var)     true

(constant (global 'foo))

(global? 'foo)     true


history

syntax: (history [bool-params])

history は、内包している関数の呼び出し履歴のリストを返します。 オプションの bool-params がなければ、関数シンボルのリストが返されます。 最初のシンボルは、内包している関数名です。オプションの bool-paramstrue に評価されると、呼び出し引数がシンボルに含まれます。
history returns a list of the call history of the enclosing function. Without the optional bool-params, a list of function symbols is returned. The first symbol is the name of the enclosing function. When the optional bool-params evaluates to true, the call arguments are included with the symbol.



(define (foo x y) 
    (bar (+ x 1) (* y 2)))

(define (bar a b) 
    (history))

; history returns names of calling functions
(foo 1 2)  (bar foo)

; the addtional 'true' forces inclusion of callpatterns
(define (bar a b) 
    (history true))

(foo 1 2)  ((bar (+ x 1) (* y 2)) (foo 1 2))


if

syntax: (if exp-condition exp-1 [exp-2])
syntax: (if exp-cond-1 exp-1 exp-cond-2 exp-2 [ ... ])

exp-condition の値が nil か空リストでないなら exp-1 の評価結果が返ります その逆では exp-2 の値が返ります。 その時、exp-2 がない場合は exp-condition(訳注:つまり nil か空リスト)が返ります。
If the value of exp-condition is neither nil nor an empty list, the result of evaluating exp-1 is returned; otherwise, the value of exp-2 is returned. If exp-2 is absent, the value of exp-condition is returned.

同時に if は、アナフォリック・システム変数 $itif の条件式の値をセットします。
if also sets the anaphoric system variable $it to the value of the conditional expression in if.

(set 'x 50)                    50
(if (< x 100) "small" "big")   "small"
(set 'x 1000)                  1000
(if (< x 100) "small" "big")   "big"
(if (> x 2000) "big")          nil

; more than one statement in the true or false
; part must be blocked with (begin ...)
(if (= x y)
  (begin
    (some-func x)
    (some-func y))
  (begin
    (do-this x y)
    (do-that x y))
)

; if also sets the anaphoric system variable $it
(set 'lst '(A B C))
(if lst (println (last $it)))   C

if の第二形式では、条件-本体ペアの式群を括弧で囲むことなしに、cond のように動作します。 この形式の if は引数を無制限に持つことができます。
The second form of if works similarly to cond, except it does not take parentheses around the condition-body pair of expressions. In this form, if can have an unlimited number of arguments.

(define (classify x)
(if
(< x 0) "negative"
(< x 10) "small"
(< x 20) "medium"
(>= x 30) "big"
"n/a"))

(classify 15)    "medium"
(classify 100)   "big"
(classify 22)    "n/a"
(classify -10)   "negative"

最後の式 "n/a" は、オプションです。 このオプション式が無い時は、式(>= x 30) の評価が返ります。 この振る舞いは伝統的な cond と厳密に同じですが、条件-式ペアの括弧は必要ありません。
The last expression, "n/a", is optional. When this option is omitted, the evaluation of (>= x 30) is returned, behaving exactly like a traditional cond but without requiring parentheses around the condition-expression pairs.

いずれにせよ、完全な if 式は、常に最後に評価された式か条件を返します。
In any case, the whole if expression always returns the last expression or condition evaluated.

関数 whenunless も見てください。
See also the when and unless functions.



ifft

syntax: (ifft list-num)

FFT 法(高速フーリエ変換)を使って、複素数リスト list-num の離散的逆フーリエ変換を計算します。 各複素数は、実数部とそれに続く虚数部で指定されます。 実数部のみ使う場合は、虚数部に 0.0(ゼロ)をセットします。 list-num の要素数が 2 のべき乗でない場合、ifft はリストをゼロで埋めて要素数を増やします。 複素数の虚数部が 0 の時は、単なる数値が使えます。
Calculates the inverse discrete Fourier transform on a list of complex numbers in list-num using the FFT method (Fast Fourier Transform). Each complex number is specified by its real part, followed by its imaginary part. In case only real numbers are used, the imaginary part is set to 0.0 (zero). When the number of elements in list-num is not an integer power of 2, ifft increases the number of elements by padding the list with zeroes. When complex numbers are 0 in the imaginary part, simple numbers can be used.

(ifft (fft '((1 0) (2 0) (3 0) (4 0)))) 
 ((1 0) (2 0) (3 0) (4 0))

;; when imaginary part is 0, plain numbers work too

(ifft (fft '(1 2 3 4))) 
 ((1 0) (2 0) (3 0) (4 0))

ifft の逆操作は、関数 fft です。
The inverse operation of ifft is the fft function.



import 

syntax: (import str-lib-name str-function-name ["cdecl"])
syntax: (import str-lib-name str-function-name str-return-type [str-param-type . . .])
syntax: (import str-lib-name)

str-lib-name の名前の共有ライブラリから str-function-name で指定された関数を導入します。 構文の使い方によっては、戻り値の文字列ラベルやパラメータ型を指定できます。
Imports the function specified in str-function-name from a shared library named in str-lib-name. Depending on the syntax used, string labels for return and parameter types can be specified

str-lib-name のライブラリがシステムのライブラリ・パスに無いなら、フル・パスを指定する必要があります。
If the library in str-lib-name is not in the system's library path, the full path name should be specified.

関数は一度だけで導入されます。同じ関数を繰り返して導入しても、ただ同じ関数の――すでに割り当てられた――アドレスが返るだけです。
A function can be imported only once. A repeated import of the same function will simply return the same - already allocated - function address.

libffi が可能なバージョン――第二拡張構文が使える版――では、導入されたシンボルは変更から保護され、constant による変更のみ許されます。
On libffi enabled versions - capable of the second extended syntax - imported symbols are protected against change and can only be modified using constant.

第三構文―― OSX、Linux、他の Unix 上でのみ――は導入関数を指定せずにライブラリを予め読み込みます。これは、他の導入ライブラリが内部的に必要とする関数へアクセスする時に必要です。
The third syntax - on OSX, Linux and other Unix only - allows pre-loading libraries without importing functions. This is necessary when other library imports need access internally to other functions from pre-loaded libraries.

import は正しく使わないと、システム・バス・エラーを引き起こし、newLISP をクラッシュさせるか、不安定な状態にします。
Incorrectly using import can cause a system bus error or a segfault can occur and crash newLISP or leave it in an unstable state.

The simple import syntax(単純 import 構文)

ほとんどのライブラリ関数は単純な第一構文を使って導入できます。 この形式は全ての newLISP コンパイル派生品に有ります。 API は関数の引数全てを cdeclstdcall 規則のスタックで渡されるものと期待しています。 32 ビットのプラットフォームでは、整数、文字列のポインタ、浮動小数点数値のバッファをパラメータとして渡すことができます。 64 ビットのプラットフォームでは、整数のみを渡すことができ、浮動小数点数値は渡すことができません。 戻り値としては、32 ビット値 か 64 ビット値とポインタのみが許されます。 浮動小数点数を戻すことはできません。 文字列は、get-string 補助関数を使って取り出す必要があります。 このような制限がありますが、配布中に含まれるほとんどのモジュールは、この単純 import API を使っています。
Most library functions can be imported using the simpler first syntax. This form is present on all compile flavors of newLISP. The API expects all function arguments to be passed on the stack in either cdecl or stdcall conventions. On 32-bit platforms, integers, pointers to strings and buffers sometimes floating point values can be passed as parameters. On 64-bit platforms only integers can be passed but no floating point values. As return values only 32-bit or 64-bit values and pointers are allowed. No floating point numbers can be returned. Strings must be retrieved with the get-string helper function. Regardless of these limitations, most modules included in the distribution use this simple import API.

ポインタが文字列や構造体を指すなら、次の補助関数がデータの取り出しに使えます:get-charget-intget-floatget-stringpackunpack
If pointers are returned to strings or structures the following helper functions can be used extract data: get-char, get-int, get-float, get-string, unpack

構造体データのポインタを渡すためには、次の関数がデータのパックやアドレス計算の助けとなります:addresspack
To pass pointers for data structures the following functions help to pack data and calculate addresses: address, pack.

newLISP のデータ型を導入した関数で必要なデータ型に変換するには、64 ビット浮動小数点数には float を、32 ビット浮動小数点数には flt を、32 ビット整数には int を使います。 デフォルトでは、newLISP 浮動小数点数には 64 ビット浮動小数点数を、整数には 32 ビット整数を、文字列には文字列アドレス(C 言語のポインタ)の 32 ビット整数を渡します。 浮動小数点数は 32 ビット版newLISP とライブラリでのみ使えます。 64 ビット環境で浮動小数点数を使うためには、拡張 import 構文を使います。
To transform newLISP data types into the data types needed by the imported function, use the functions float for 64-bit double floats, flt for 32-bit floats, and int for 32-bit integers. By default, newLISP passes floating point numbers as 64-bit double floats, integers as 32-bit integers, and strings as 32-bit integers for string addresses (pointers in C). Floats can only be used with 32-bit versions of newLISP and libraries. To use floating point numbers in a 64-bit environment use the extended import syntax.

;; define LIBC platform independent

(define LIBC (lookup ostype '(
("Windows" "msvcrt.dll")
("OSX" "libc.dylib")

(import LIBC "printf")
(printf "%g %s %d %c\n" 1.23 "hello" 999 65)
1.23 hello 999 A
 17 ; return value

;; import MS Windows DLLs in 32-bit versions 

(import "kernel32.dll" "GetTickCount")   GetTickCount
(import "user32.dll" "MessageBoxA")      MessageBoxA
(GetTickCount)                           3328896

最初の例では、文字列 "1.23 hello 999 A" が副次効果で出力され、値 17(出力文字数)が返ります。 この方法で、どのような C 関数でも共有ライブラリから導入できます。
In the first example, the string "1.23 hello 999 A" is printed as a side effect, and the value 17 (number of characters printed) is returned. Any C function can be imported from any shared library in this way.

メッセージ・ボックスの例では、コンソール・ウィンドウの後ろに隠れているかもしれませんが、Windows ダイアログ・ボックスがポップ・アップします。 メッセージ・ボックスの 'OK' ボタンを押されるまで、コンソール・プロンプトに結果が返りません。
The message box example pops up a Windows dialog box, which may be hidden behind the console window. The console prompt does not return until the 'OK' button is pressed in the message box.

;;this pops up a message box

(MessageBoxA 0 "This is the body" "Caption" 1) 

他の例は、MS Windows DLL 関数のいくつかの導入と 即値参照 による引数の与え方を示します。 文字列や数を参照で渡す時は、事前に場所を用意しておく必要があります。
The other examples show several imports of MS Windows DLL functions and the details of passing values by value or by reference. Whenever strings or numbers are passed by reference, space must be reserved beforehand.

(import "kernel32.dll" "GetWindowsDirectoryA")

;; allocating space for a string return value
(set 'str (dup "\000" 64))  ; reserve space and initialize

(GetWindowsDirectoryA str (length str))

str   "C:\\WINDOWS\000\000\000 ... "

;; use trim or get-string to cut of binary zeros
(get-string str)   "C:\\WINDOWS"
(trim str)         "C:\\WINDOWS"

(import "kernel32.dll" "GetComputerNameA")

;; allocate memory and initialize to zeros
(set 'str (dup "\000" 64))
(set 'len (length str)

;; call the function
;; the length of the string is passed as address reference 
;; string str is automatically past by address (C pointer)
(GetComputerNameA str (address len)) 

str   "LUTZ-PC\000\000 ... "

(trim str)   "LUTZ-PC"

import は関数のアドレスを返し、導入した関数に別の名前を割り当てるのに使えます。
import returns the address of the function, which can be used to assign a different name to the imported function.

(set 'imprime (import "libc.so.6" "printf")) 
 printf@400862A0

(imprime "%s %d" "hola" 123)                 
 "hola 123"

MS Windows や Cygwin 版の newLISP は、DLLライブラリ・ルーチンの呼び出しに、デフォルトで標準呼び出し stdcall 手続きを使います。 これは、MS Windows オペレーティング・システムに属する DLL (例えば、odbc32.dll) の呼び出しには必要なことです。 多くのサード・パーティの DLL は、C 宣言 cdecl 呼び出し手続きでコンパイルされ、関数を導入する時に追加する最後の引数に文字列 "cdecl" の指定を必要とするかもしれません。 macOS や Linux や 他の Unix システムでコンパイルされたnewLISP は、デフォルトで cdecl 呼び出し手続きを使いますので、追加の文字列は無視します。
The MS Windows and Cygwin versions of newLISP uses standard call stdcall conventions to call DLL library routines by default. This is necessary for calling DLLs that belong to the MS Windows operating system. Most third-party DLLs are compiled for C declaration cdecl calling conventions and may need to specify the string "cdecl" as an additional last argument when importing functions. newLISP compiled for macOS, Linux and other Unix systems uses the cdecl calling conventions by default and ignores any additional string.

;; force cdecl calling conventions on MS Windows
(import "sqlite.dll" "sqlite_open" "cdecl")   sqlite_open <673D4888>

導入した関数は、14個の引数を取るかもしれません。 浮動小数点数の引数は、二つの場所を取ることに注意してください。 (例えば、十四個のパラメータの内、十個を取って五つの浮動小数点はを渡す)。
Imported functions may take up to fourteen arguments. Note that floating point arguments take up two spaces each (e.g., passing five floats takes up ten of the fourteen parameters).

The extended import syntax(拡張 import 構文)

拡張 import API は第二構文で動作します。 それは、よく知られている libffi ライブラリに基づいており、ほとんどの OS プラットフォームに予めインストールされています。 この拡張 import API を使ってコンパイルされたバージョンの newLISP なら、newLISP 開始時の表示に libffi の単語が表示されているでしょう。 libffi が使えるかどうかは、関数 sys-info を使ってもチェックできます。
The extended import API works with the second syntax. It is based on the popular libffi library which is pre-installed on most OS platforms. The startup banner of newLISP should show the word libffi indicating the running version of newLISP is compiled to use the extended import API. The function sys-info can also be used to check for libffi-support.

この API は、パラメータ渡しや戻り値に C言語のデータ型を使って動作します。 API は、パラメータの型が import 構文で指定されている必要があります。 型指定には、型の文字列ラベルを使います。 拡張 import API で書かれたプログラムは、32 ビットと 64 ビットの newLISP とライブラリで変更することなく、走るでしょう。 補助関数を使うことなしに、整数、浮動小数点数、文字列を戻せます。
The API works with all atomic C data types for passed parameters and return values. The extended API requires that parameter types are specified in the import statement as string type labels. Programs written with extended import API will run without change on 32-bit and 64-bit newLISP and libraries. Integers, floating point values and strings can be returned without using helper functions.

str-return-type の戻り値や str-param-type の関数パラメータには、次の型を指定できます:
The following types can be specified for the return value in str-return-type and for function parameters in str-param-type:

labelC type for return value and argumentsnewLISP return and argument type
"void"voidnil is returned for return type
"byte"byte unsigned 8 bitinteger
"char"char signed 8 bitinteger
"unsigned short int"unsigned short int 16 bitinteger
"short int"short int signed 16 bitinteger
"unsigned int"unsigned int 32 bitinteger
"int"int signed 32 bitinteger
"long"long signed 32 or 64 bit depending on platforminteger
"long long"long long signed 64 bitinteger
"float"float 32 bitIEEE-754 64 bit float cut to 32-bit precision
"double"double 64 bitIEEE-754 64 bit float
"char*"char* 32 or 64 bit ptr depending on platformdisplayable string return (zero terminated)
string buffer arg (no addr. since 10.4.2)
"void*"void* 32 or 64 bit ptr depending on platforminteger address return
either string buffer or integer address arg

"char*" 型と "void* 型は libffi 内で同等に扱われ、代替可能です。 渡される引数の型と戻り値の型次第で、どちらかが使われます。
The types "char*" and "void* can be interchanged and are treated identical inside libffi. Depending on the type of arguments passed and the type of return values, one or the other is used.

集合型は関数 struct を使って構築でき、引数や戻り値に使うことができます。
Aggregate types can be composed using the struct function and can be used for arguments and return values

次の例がしめしているのは、拡張 import 構文で浮動小数点数や文字列も戻り値をどのように処理できるかです:
The following examples show how the extended import syntax can handle return values of floating point values and strings:

;; return a float value, LIBC was defined earlier
;             name   return   arg
(import LIBC "atof" "double" "char*")
(atof "3.141")  3.141

;; return a copied string
;             name     return  arg-1   arg-2
(import LIBC "strcpy" "char*" "char*" "char*")
(set 'from "Hello World")

(set 'to (dup "\000" (length from))) ; reserve memory
(strcpy to from)  "Hello World"

"char*" 型は文字列バッファのみを取ります。 "void* 型は入力として、文字列バッファかメモリ・アドレスのどちらかを取ることができます。 戻り値の型として "void*" を使うと、結果のバッファ・アドレスが戻ります。 これは、構造体データへのポインタを返す時に役立ちます。 このポインタから構造体の中身を取り出すには、unpackstruct を使います。 次の例では、戻り値の型を void* に変えています:
The char* type takes a string buffer only. The "void* type can take either a string buffer or a memory address number as input. When using "void*" as a return type the address number of the result buffer will be returned. This is useful when returning pointers to data structures. These pointers can then be used with unpack and struct for destructuring. In the following example the return type is changed to void*:

(import LIBC "strcpy" "void*" "char*" "char*")
(set 'from "Hello World")
(set 'to (dup "\000" (length from)))

(strcpy to from)        2449424
(address to)            2449424
(unpack "s11" 2449424)  "Hello World"
(get-string 2449424)    "Hello World"
to                      "Hello World"

newLISP の文字列は常にアドレス参照で渡されます。
A newLISP string is always passed by it's address reference.

もっと複雑な例は、この OpenGL demo を見てください。
For a more complex example see this OpenGL demo.

Memory management

導入した外部関数により実行された割り当ては、導入したAPIにその呼び出し(機能)がないなら、マニュアルで解除しなければなりません。 Code Patterns in newLISP の例(訳注:Memory management の項)を見てください。
Any allocation performed by imported foreign functions has to be de-allocated manually if there's no call in the imported API to do so. See the Code Patterns in newLISP document for an example.

参照渡しで外部関数を呼び出す場合、 変数用のメモリを newLISP 側で予め割り当てておく必要がありますが、 ——(訳注:前記)GetWindowsDirectoryA の導入例を見てください——それゆえ、メモリはマニュアルで解放する必要はありません。 newLISP によって自動的に管理されています。
In case of calling foreign functions with passing by reference, memory for variables needs to be allocated beforehand by newLISP — see import of GetWindowsDirectoryA above — and hence, memory needs not be deallocated manually, because it is managed automatically by newLISP.



inc !

syntax: (inc place [num])

place の数値を 1.0 かオプションの数値 num 分加算し、 結果を返します。 inc は浮動小数点数計算を実行し、渡された整数値を浮動小数点型に変換します。
Increments the number in place by 1.0 or by the optional number num and returns the result. inc performs float arithmetic and converts integer numbers passed into floating point type.

place はシンボルかリスト構造内の位置、式によって返される数値のいずれかです。
place is either a symbol or a place in a list structure holding a number, or a number returned by an expression.

(set 'x 0)     0
(inc x)        1
x              1
(inc x 0.25)   1.25
x              1.25
(inc x)        2.25

シンボル placenil が入っているなら、0.0 が入っているとして扱われます:
If a symbol for place contains nil, it is treated as if containing 0.0:

z              nil
(inc z)        1

(set 'z nil)
(inc z 0.01)   0.01

リスト構造内の位置や式によって返される数値も更新可能です:
Places in a list structure or a number returned by another expression can be updated too:

(set 'l '(1 2 3 4))

(inc (l 3) 0.1)  4.1

(inc (first l))  2

l  (2 2 3 4.1)

(inc (+ 3 4))  8

整数モードでの数値の加算には、関数 ++ を使ってください。 浮動小数点モードの減算には、dec を使ってください。
Use the ++ function for incrementing numbers in integer mode. Use dec to decrement numbers in floating point mode.



index

syntax: (index exp-predicate exp-list)

述部 exp-predicate をリスト exp-list の各要素に適用し、exp-predicate が true となる要素の位置のリストが返ります。
Applies the predicate exp-predicate to each element of the list exp-list and returns a list containing the indices of the elements for which exp-predicate is true.

(index symbol? '(1 2 d 4 f g 5 h))   (2 4 5 7)

(define (big? x) (> x 5))   (lambda (x) (> x 5))

(index big? '(1 10 3 6 4 5 11))   (1 3 6)

(select '(1 10 3 6 4 5 11) '(1 3 6))  (10 6 11)

述部は、組込述語かユーザ定義関数かラムダ式です。
The predicate may be a built-in predicate, a user-defined function, or a lambda expression.

要素それ自体を返したい時は、関数 filter を使ってください。
Use the filter function to return the elements themselves.



inf?

syntax: (inf? float)

この関数は、float の値が無限大なら trueを返し、そうでなければ nil を返します。
If the value in float is infinite the function returns true else nil.

(inf? (div 1 0))  true

(div 0 0)  NaN

整数をゼロで割る、すなわち (/ 1 0) は "division by zero" エラーを引き起こして無限大にならないので、注意してください。 浮動小数点数が有効かどうかをチェックする NaN? も見てください。
Note that an integer division by zero e.g. (/ 1 0) will throw an "division by zero" error and not yield infinity. See also NaN? to check if a floating point number is valid.



int

syntax: (int exp [exp-default [int-base]])

exp の式が数値か文字列なら、結果は整数に変換されて返されます。 exp が整数に変換できない時は、nilexp-default の評価結果が返ります。 この関数は、ユーザ入力やテキスト解析による文字列の変換によく使われます。 exp が文字列に評価される場合、文字列は数字か一個以上のスペースか +- サインで始まっていなければなりません。 16進数文字列は '0x'、8進数文字列は '0'(ゼロ)で始まっている必要があります。 特に指定が無く exp が有効でなければ、int はデフォルト値として nil を返します。
If the expression in exp evaluates to a number or a string, the result is converted to an integer and returned. If exp cannot be converted to an integer, then nil or the evaluation of exp-default will be returned. This function is mostly used when translating strings from user input or from parsing text. If exp evaluates to a string, the string must start with a digit; one or more spaces; or the + or - sign. The string must begin with '0x' for hexadecimal strings or '0' (zero) for octal strings. If exp is invalid, int returns nil as a default value if not otherwise specified.

第二オプション・パラメータには、変換基数を指定できます。
A second optional parameter can be used to force the number base of conversion to a specific value.

9,223,372,036,854,775,807 より大きい整数は、9,223,372,036,854,775,807 に切り捨てられます。 -9,223,372,036,854,775,808 より小さい整数は、-9,223,372,036,854,775,808 に切り詰められます。
Integers larger than 9,223,372,036,854,775,807 are truncated to 9,223,372,036,854,775,807. Integers smaller than -9,223,372,036,854,775,808 are truncated to -9,223,372,036,854,775,808.

int の第二形式として)浮動小数点からの変換の時、浮動小数点数が整数の最大値より大きい値か最小値より小さい値なら、それらは切り捨てられます。 NaN に評価される浮動小数点数は、0(ゼロ)に変換されます。
When converting from a float (as in the second form of int), floating point values larger or smaller than the integer maximum or minimum are also truncated. A floating point expression evaluating to NaN is converted to 0 (zero).

(int "123")           123
(int " 123")          123
(int "a123" 0)        0
(int (trim " 123"))   123
(int "0xFF")          255
(int "0b11111")       31
(int "055")           45
(int "1.567")         1
(int 1.567)           1

(integer? 1.00)         nil
(integer? (int 1.00))   true

(int "1111" 0 2)   15   ; base 2 conversion
(int "0FF" 0 16)   255  ; base 16 conversion

(int 'xyz)      nil
(int 'xyz 0)    0
(int nil 123)   123

(int "abc" (throw-error "not a number"))  
 ERR: user error : not a number

(print "Enter a num:")
(set 'num (int (read-line)))

(int (bits 12345) 0 2)  12345

基数 2 の時の int の逆関数は bits です。
The inverse function to int with base 2 is bits.

引数を浮動小数点数に変換する時は、関数 float を使ってください。
Use the float function to convert arguments to floating point numbers.



integer?

syntax: (integer? exp)

exp の値が整数の時のみ true が返り、それ以外では nil が返ります。
Returns true only if the value of exp is an integer; otherwise, it returns nil.

(set 'num 123)   123
(integer? num)   true


intersect

syntax: (intersect list-A list-B)
syntax: (intersect list-A list-B bool)

第一構文の intersect は、list-Alist-B の両方で見つかる各要素の一つのコピーからなるリストを返します。
In the first syntax, intersect returns a list containing one copy of each element found both in list-A and list-B.

(intersect '(3 0 1 3 2 3 4 2 1) '(1 4 2 5))  
 (2 4 1)

第二構文の(訳注:list モードで動作する)intersect は、list-B に存在する list-A の全て要素からなるリストを返します。 list-A 内で重複している要素は削除されません。 bool は、true に評価される式か nil 以外の値です。
In the second syntax, intersect returns a list of all elements in list-A that are also in list-B, without eliminating duplicates in list-A. bool is an expression evaluating to true or any other value not nil.

(intersect '(3 0 1 3 2 3 4 2 1) '(1 4 2 5) true)
 (1 2 4 2 1)

集合関数の differenceuniqueunion も見てください。
See also the set functions difference, unique and union.



invert

syntax: (invert matrix [float-pivot])

matrix の二次元行列の逆行列を返します。 行列は行と列が同じ数である正方で、(逆行列を持つ)非特異 でなければなりません(訳注:つまり、正則行列)。 逆行列は、線型方程式のシステム(例えば、統計の重回帰)の解法に使うことができます。 newLISP は逆行列の検出に、行列のLU分解を使っています。
Returns the inversion of a two-dimensional matrix in matrix. The matrix must be square, with the same number of rows and columns, and non-singular (invertible). Matrix inversion can be used to solve systems of linear equations (e.g., multiple regression in statistics). newLISP uses LU-decomposition of the matrix to find the inverse.

オプションで、float-pivot0.0 か非常に小さい値を指定できます。 この値は、LU分解アルゴリズムで特異行列(訳注:逆行列を持たない行列)を処理する時にゼロになるピボット要素の代わりになります。
Optionally 0.0 or a very small value can be specified in float-pivot. This value substitutes pivot elements in the LU-decomposition algorithm, which result in zero when the algorithm deals with a singular matrix.

行列の次元は、行数と最初の行の要素数の積で定義されます。 非矩形行列上の見つからない要素は 0.0(ゼロ)になります。 行列は、入れ子のリストでも array でも可能です。
The dimensions of a matrix are defined by the number of rows times the number of elements in the first row. For missing elements in non-rectangular matrices, 0.0 (zero) is assumed. A matrix can either be a nested list or an array.

(set 'A '((-1 1 1) (1 4 -5) (1 -2 0)))
(invert A)   ((10 2 9) (5 1 4) (6 1 5))
(invert (invert A))  ((-1 1 1) (1 4 -5) (1 -2 0))

; solve Ax = b for x
(multiply (invert A) '((1) (2) (3)))  ((41) (19) (23))

; treatment of singular matrices
(invert '((2 -1) (4 -2)))         nil
(invert '((2 -1) (4 -2)) 0.0)     ((inf -inf) (inf -inf))
(invert '((2 -1) (4 -2)) 1e-20)   ((5e+19 -2.5e+19) (1e+20 -5e+19)) 

行列が 特異行列 で逆行列を持たず、float-pivot が指定されていなければ、invertnil を返します。
invert will return nil if the matrix is singular and cannot be inverted, and float-pivot is not specified.

ここで示されたリスト上の操作は全て、アレイに対しても有効です。
All operations shown here on lists can be performed on arrays, as well.

行列関数の detmatmultiplytranspose も見てください。
See also the matrix functions det, mat, multiply and transpose.



irr

syntax: (irr list-amounts [list-times [num-guess]])

期間あたりのキャッシュ・フローの内部収益率を計算します。 内部収益率は、キャシュ・フローの現在の価値を 0.0(ゼロ)にする金利です。 流入(負数)と流出(正数)の総額を list-amounts に指定します。 list-times に期間倍率が指定されていない場合、list-amounts は1 ずつ( 1, 2, 3 –という風に)増加する期間倍率で合計されます。 使っているアルゴリズムは、初期推定値0.5 (50%) の反復法です。 オプションで、異なる初期推定値を指定できます。 アルゴリズムは、精度が 0.000001 (0.0001%) に達した時に戻ります。 アルゴリズムが 50 回で収束しなかった時は、nil が返ります。
Calculates the internal rate of return of a cash flow per time period. The internal rate of return is the interest rate that makes the present value of a cash flow equal to 0.0 (zero). In-flowing (negative values) and out-flowing (positive values) amounts are specified in list-amounts. If no time periods are specified in list-times, amounts in list-amounts correspond to consecutive time periods increasing by 1 (1, 2, 3—). The algorithm used is iterative, with an initial guess of 0.5 (50 percent). Optionally, a different initial guess can be specified. The algorithm returns when a precision of 0.000001 (0.0001 percent) is reached. nil is returned if the algorithm cannot converge after 50 iterations.

irr は、異なるタイプの投資間の決定によく使われます。
irr is often used to decide between different types of investments.

(irr '(-1000 500 400 300 200 100))  
 0.2027

(npv 0.2027 '(500 400 300 200 100)) 
 1000.033848 ; ~ 1000

(irr '(-1000 500 400 300 200 100) '(0 3 4 5 6 7)) 
 0.0998

(irr '(-5000 -2000 5000 6000) '(0 3 12 18)) 
 0.0321

1,000 の初期投資が一年後に 500 をもたらし、二年後に 400 と続き、5 年を過ぎると最終的に 0.0(ゼロ)となるならば、それは年利約 20.2 %の配当に相当します。 次の行(訳注:例題の二行目)は、 irrnpv の関係を示しています。 (訳注:例題の三行目は、)三年後から回収を始めたいのであれば、たった 9.9 %の配当で済みます。
If an initial investment of 1,000 yields 500 after the first year, 400 after two years, and so on, finally reaching 0.0 (zero) after five years, then that corresponds to a yearly return of about 20.2 percent. The next line demonstrates the relation between irr and npv. Only 9.9 percent returns are necessary when making the first withdrawal after three years.

例題の最後では、証券を最初に 5,000 購入し、3 カ月後別に 2,000 購入したとしています。 一年後(訳注:12ヵ月後)、5,000 分の証券を売ったとします。 18ヵ月後に残りの証券を売って 6,000 を得たとします。 この場合の内部収益率は、一ヶ月あたり 3.2 %となり、18ヶ月でおよそ 57 %です。
In the last example, securities were initially purchased for 5,000, then for another 2,000 three months later. After a year, securities for 5,000 are sold. Selling the remaining securities after 18 months renders 6,000. The internal rate of return is 3.2 percent per month, or about 57 percent in 18 months.

関数 fvnpernpvpmtpv も見てください。
See also the fv, nper, npv, pmt, and pv functions.



json-error

syntax: (json-error)

json-parse が JSON データの変換し失敗して nil を返す時、この関数でエラーの詳細と解析時の最終位置を引き出せます。
When json-parse returns nil due to a failed JSON data translation, this function retrieves an error description and the last scan position of the parser.

; failed parse returns nil
(json-parse [text]{"address" "http://example.com"}[/text])  nil

; inspect the error information
(json-error)  ("missing : colon" 11)


json-parse

syntax: (json-parse str-json-data)

この関数は JSON形式のテキストを解析し、newLISP のS式に変換します。 ECMA-262 標準に従う全てのデータ型が変換されます。 JSON の false 値や null 値は、newLISP のシンボル式中では false シンボルや null シンボルで表現されます。JSON 中のアレイは newLISP 中ではリストで表現されます。JSON オブジェクト・データから結果として得られるリストは、assoclookupref を使って処理することができます。
This function parses JSON formatted text and translates it to newLISP S-expressions. All data types conforming to the ECMA-262 standard are translated. The JSON values false and null will be represented by the symbols false and null in the symbolic newLISP expressions. Arrays in JSON will be represented by lists in newLISP. The resulting lists from JSON object data can be processed using assoc, lookup and ref.

json-parse は、認識されなかった JSON の属性値や誤った JSON 構文に対して nil を返し、そのエラー文の取り出しには json-error が使えます。
For JSON attribute values not recognized or wrong JSON syntax, json-parse returns nil and json-error can be used to retrieve the error text.

次の例は、person.json ファイルにある入れ子 JSON オブジェクトを表しています:
The following example shows a nested JSON object from a file person.json:

{
"name": "John Smith",
"age": 32,
"employed": true,
"address": {
"street": "701 First Ave.",
"city": "Sunnyvale, CA 95125",
"country": "United States"
},
"children": [
{
    "name": "Richard",
    "age": 7
},
{
    "name": "Susan",
    "age": 4
},
{
    "name": "James",
    "age": 3
}
]
}

ファイルを読み込んで解析し、結果のS式を jsp に納めます:
The file is read, parsed and the resulting S-expression stored in jsp:

(set 'jsp (json-parse (read-file "person.json")))

( ("name" "John Smith") 
("age" 32) 
("employed" true) 
("address" ( ("street" "701 First Ave.") 
       ("city" "Sunnyvale, CA 95125") 
       ("country" "United States")) ) 
("children" (
(("name" "Richard") ("age" 7)) 
(("name" "Susan") ("age" 4)) 
(("name" "James") ("age" 3))) )
)

データは assoclookupref を使って取り出せます:
Data can be extracted using assoc, lookup or ref:

; the address
(lookup "address" jsp)
 (("street" "701 First Ave.") ("city" "Sunnyvale, CA 95125") ("country" "United States"))

; the city of the address
(lookup "city" (lookup "address" jsp)) 
 "Sunnyvale, CA 95125"

; a child named Susan
(ref '(( * "Susan") *) jsp match true) 
 (("name" "Susan") ("age" 4))

; all names
(map last (ref-all '("name" *) jsp match true)) 
 ("John Smith" "Richard" "Susan" "James")

; only names of children
(map last (ref-all '("name" *) (lookup "children" jsp) match true))

("Richard" "Susan" "James")

; names of children other method
(map last (map first (lookup "children" jsp)))

("Richard" "Susan" "James")

大抵の場合、JSON オブジェクト型は解析されますが、全 JSON データ型は JSON オブジェクトの一部としてではなく、直接解析されます。 次は、JSON 配列の解析例です:
Although most of the time JSON object types are parsed, all JSON data types can be parsed directly, without occurring as part of a JSON object. The following examples show parsing of a JSON array:

; parse a JSON array data type

(json-parse "[1, 2, 3, 4, 5]")  (1 2 3 4 5)

UTF-8 が有効な newLISP バージョンが使われているなら、JSON 形式のユニコードは UTF-8 に変換されます:
When the UTF-8 capable version of newLISP is used, JSON formatted Unicode gets translated into UTF-8:

; parse a JSON object data type ands Unicode
; the outer {,} are newLISP string delimiters [text],[/text] tags could also be used
; the inner {,} are JSON object delimiters

(json-parse { {"greek letters" : "\u03b1\u03b2\u03b3\u03b4"} })  (("greek letters" "αβγδ"))

; strings longer than 2047 bytes should be delimted with [text], [/text] tags

(json-parse [text]{"greek letters" : "\u03b1\u03b2\u03b3\u03b4"}[/text])  (("greek letters" "αβγδ"))

JSON でユニコード文字を表現する16進数表記は UTF-8 版 newLISP でも使えます。
The hex-code representation of Unicoder characters in JSON is the same as can be used in UTF-8 enabled newLISP.

JSON オブジェクトは {,}," を含むので、JSON データの区切りに引用符を使うべきではありませんし、JSON データ内の全ての引用符の前にはバックスラッシュ \ を置く必要があります。 {,} 対は JSON データ内で対応が取れていれば、可能な限りの長さで使えます。 安全な区切りは [text], [/text] タグです —— これなら newLISP に読み取られる時の文字列特殊処理が全て抑制されるし、2047 バイトより大きいデータを区切るのにも適しています。
Because JSON objects contain {,}," characters, quotes should not be used to limit JSON data, or all quotes inside the JSON data would need a preceding backslash \. {,} braces can be used as long as braces inside the JSON data are balanced. The safest delimiter are [text], [/text] tags — they suppress all special processing of the string when read by newLISP and are delimit to delimit large data sizes greater 2047 bytes.



join

syntax: (join list-of-strings [str-joint [bool-trail-joint]])

与えられた list-of-strings の文字列のリストを(訳注:間にスペースを入れて)つなぎ合わせます。 str-joint があれば、(訳注:スペースの代わりに)結合時にそれが(訳注:接続文字として)各文字列間に挿入されます。 bool-trail-jointtrue なら、接続文字が文字列の最後にも追加されます。
Concatenates the given list of strings in list-of-strings. If str-joint is present, it is inserted between each string in the join. If bool-trail-joint is true then a joint string is also appended to the last string.

(set 'lst '("this" "is" "a" "sentence"))

(join lst " ")   "this is a sentence"

(join (map string (slice (now) 0 3)) "-")   "2003-11-26"

(join (explode "keep it together"))   "keep it together"

(join '("A" "B" "C") "-")          "A-B-C"
(join '("A" "B" "C") "-" true)     "A-B-C-"

関数 appendstringjoin 操作と逆の explode も見てください。
See also the append, string, and explode functions, which are the inverse of the join operation.



kmeans-query

syntax: (kmeans-query list-data matrix-centroids)
syntax: (kmeans-query list-data matrix-data)

最初の使い方では、kmeans-querylist-data で与えられるベクトル・データから matix-centroids で与えられる重心までのユークリッド距離を計算します。 list-data のベクトル・データは m 個の要素からなります。 事前の kmeans-train による区分けの結果である matrix-centroids の2次元リスト(訳注:リストのリストだから2次元)は km 列からなり、k 行の m 要素が重心を表しています。
In the first usage, kmeans-query calculates the Euclidian distances from the data vector given in list-data to the centroids given in matrix-centroids. The data vector in list-data has m elements. The 2-dimensional list in matrix-centroids, result from a previous kmeans-train clustering, has k rows and m columns for k centroids measuring m features.

; centroids from previous kmeans-train
K:centroids 
( (6.39 7.188333333 5.935) 
(7.925714286 3.845714286 9.198571429) 
(2.207142857 2.881428571 0.8885714286) )

(kmeans-query '(1 2 3) K:centroids) 
(8.036487279 9.475994267 2.58693657) ; distances to cluster 1, 2 and 3

データ (1 2 3) は、3番目のクラスターと最も距離の近いことがわかり、そのクラスターに属するものとして分類されるでしょう。
The data record (1 2 3) shows the smallest distance to the 3rd cluster centroid and would be classified as belonging to that cluster.

二番目の利用法では、kmeans-query は重心ではない他のデータ・ポイントのリストまでのユークリッド距離を計算します。 次の例は、ベクトル・データ (1 2 3) から kmeans-train によるデータ解析に使った元々のポイントまで距離を掲載しています。
In the second application kmeans-query calculates Euclidian distances to a list of other data points which are not centroids. The following example calculates distances of the (1 2 3) data vector to all original points from the original kmeans-train data analysis.

matix-data のデータには入れ子のリストも、二次元アレイも使えます。
The data in matrix-data can be either a nested list or a 2-dimensional array.

続けて行われる kNN(k 近傍法)解析のために、このベクトルを並べ替えることができます:
This vector could be sorted for a subsequent kNN (k Nearest Neighbor) analysis:

(kmeans-query '(1 2 3) data) 
(10.91671196 3.190626898 9.19723328 3.014415366 9.079763213 
6.83130295 8.533111976 9.624816881 6.444261013 2.013107051 
3.186549858 9.475199206 9.32936761 2.874786949 7.084638311 
10.96221237 10.50080473 3.162419959 2.423674896 9.526436899)

; show distances to members in each cluster

; for cluster labeled 1
(select (kmeans-query '(1 2 3) data) (K:clusters 0))  
(9.079763213 6.83130295 9.624816881 6.444261013 7.084638311 10.50080473)

; for cluster labeled 2
(select (kmeans-query '(1 2 3) data) (K:clusters 1)) 
(10.91671196 9.19723328 8.533111976 9.475199206 9.32936761 10.96221237 9.526436899)

; for cluster labeled 3
(select (kmeans-query '(1 2 3) data) (K:clusters 2)) 
(3.190626898 3.014415366 2.013107051 3.186549858 2.874786949 3.162419959 2.423674896)

最小距離が第3クラスターのオフセットが2(つまり3番目)のデータポイントにあることがわかります。
We see that the smallest distances are shown for the data points in the 3rd cluster at offset 2.

list-data の要素の数がデータや重心行列の列数と異なる場合、ユークリッド距離の計算のためにより小さい方が取られます。 これは、データ行列の最終列が意味のあるデータでない場合に役立ちます。
If the numbers of elements - features - in records of list-data is different from the number of columns in the data or centroid matrix, then the smaller is taken for calculating the Euclidian distances. This is useful when the last column of the data matrix does not contain feature data, but labels identifying the cluster membership of a data point.



kmeans-train

syntax: (kmeans-train matrix-data int-k context [matrix-centroids])

この関数は、matrix-data に対して K 平均法クラスター解析を行います。 n 個のデータ全てが int-k 個のグループの中に別々に区分けされます。
The function performs Kmeans cluster analysis on matrix-data. All n data records in matrix-data are partitioned into a number of int-k different groups.

n * mmatrix-data やオプションの k * mmatrix-centroids には、入れ子のリストも2次元アレイも使えます。
Both, the n * m matrix-data and the optional k * m matrix-centroids can be either nested lists or 2-dimensional arrays.

この K 平均法アルゴリズムはクラスタ重心からの内部クラスター距離の二乗和(SSQ)を最小するように動作します。繰り返し動作する度に、重心は最終位置に近づきます。データ一式が同じでも、最終結果は最初の重心位置次第です。重心の初期値を適切に選択することで処理速度が早められ、望んでいない極小値も避けられます。
The Kmeans algorithm tries to minimize the sum of squared inner cluster distances (SSQ) from the cluster centroid. With each iteration the centroids get moved closer to their final position. On some data sets, the end result can depend on the starting centroid points. The right choice of initial centroids can speed up the process and avoid not wanted local minima.

オプションの matrix-centroids が与えられない時、各クラスターにはランダムデータ行が初期値として割り当てられ、重心の計算が始まります。
When no optional matrix-centroids are given, kmeans-train will assign an initial random cluster membership to each data row and calculate starting centroids.

kmeans-train は SSQ 全体のベクトルを返します。SSQ はクラスター内の重心からの全クラスターの内部距離の二乗和です。 繰り返しアルゴリズムは、 SSQ の変化が 1e-10 より小さくなった時に止まります。
kmeans-train returns a vector of total SSQs, the sum of squared inner distances from the centroid inside the cluster for all clusters. The Iterating algorithm stops when the change of SSQ from one to the next iteration is less than 1e-10.

他の解析結果は、コンテキスト 変数の中にリストとして保存されています。
Other results of the analysis are stored as lists in variables of context.

次の例は、 m = 3 の 20 個のデータを解析し、 k = 3 のクラスターに区分けします。 k = 3 より大きい数を試すことができます。 平均内部クラスター距離で計測して高密度になるクラスターが目標となる結果です。
The following example analyses 20 data records measuring m = 3 features and tries to partition data into k = 3 clusters. Other numbers than k = 3 could be tried. The target is a result with few clusters of high density measured by the average inner cluster distances.

(set 'data '(
(6.57 4.96 11.91) 
(2.29 4.18 1.06) 
(8.63 2.51 8.11) 
(1.85 1.89 0.11) 
(7.56 7.93 5.06) 
(3.61 7.95 5.11) 
(7.18 3.46 8.7) 
(8.17 6.59 7.49) 
(5.44 5.9 5.57) 
(2.43 2.14 1.59) 
(2.48 2.26 0.19) 
(8.16 3.83 8.93) 
(8.49 5.31 7.47) 
(3.12 3.1 1.4) 
(6.77 6.04 3.76) 
(7.01 4.2 11.9) 
(6.79 8.72 8.62) 
(1.17 4.46 1.02) 
(2.11 2.14 0.85) 
(9.44 2.65 7.37)))

(kmeans-train data 3 'MAIN:K)  
(439.7949357 90.7474276 85.06633163 82.74597619)

; cluster membership
K:labels  (2 3 2 3 1 1 2 1 1 3 3 2 2 3 1 2 1 3 3 2)

; the centroid for each cluster
K:centroids 
( (6.39 7.188333333 5.935) 
(7.925714286 3.845714286 9.198571429) 
(2.207142857 2.881428571 0.8885714286) )

戻り値は SSQ のリストで、各繰り返しで内部距離の二乗和が小さくなる様子を見せてくれます。 K:labels のリストは各データ点がどのクラスターにあるのかを示しています。データ点と同じ位置の数字がクラスターの番号です。
The returned list of SSQs shows how in each iteration the sum of inner squared distances decreases. The list in K:labels shows the membership fo each data point in the same order as in the data.

K:centroids の重心は、kmeans-query を使う際に、新データの区分けに使うことができます。
The centroids in K:centroids can be used for later classification of new data records using kmeans-query.

クラスターの要素からクラスター重心までの内部偏差 K:deviations は、クラスターの混み具合を示しています。 公式的には、ユークリッド距離の計算や標準偏差の計算と似たような計算です。 偏差を二乗して各クラスターの大きさを掛けると各クラスターの内部 SSQ になります:
The average inner K:deviations from cluster members to their centroid show how dense a cluster is packed. Formally, deviations are calculated similarly to Euclidian distances and to standard deviations in conventional statistics. Squaring the deviations and multiplying each with their cluster size (number of members in the cluster) shows the inner SSQ of each cluster:

; average inner deviations of cluster members to the centroid
; deviation = sqrt(ssq-of-cluster / n-of-cluster)
K:deviations   (2.457052209 2.260089397 1.240236975)

; calculating inner SSQs from cluster deviations
(map mul '(6 7 7) (map mul K:deviations K:deviations)) 
(36.22263333 35.75602857 10.76731429) ; inner SSQs

; SSQ from last iteration as sum of inner SSQs
(apply add '(36.22263333 35.75602857 10.76731429))  82.74597619

K:clusters は、各クラスターのデータが元データではどの位置にあるかを与えてくれます。 これを使って、データのさらなる解析にのために、個々のクラスターを個別に取り出せます:
K:clusters gives indices of data records into the original data for each cluster. With these, individual clusters can be extracted from the data for further analysis:

; ceach of the result clusters with indices into the data set
K:clusters  
( (4 5 7 8 14 16) 
(0 2 6 11 12 15 19) 
(1 3 9 10 13 17 18) )

; cluster of data records labeled 1 at offset 0
(select data (K:clusters 0)) 
( (7.56 7.93 5.06) 
(3.61 7.95 5.11) 
(8.17 6.59 7.49) 
(5.44 5.9 5.57) 
(6.77 6.04 3.76) 
(6.79 8.72 8.62) )

; cluster of data records labeled 2 at offset 1
(select data (K:clusters 1)) 
( (6.57 4.96 11.91) 
(8.63 2.51 8.11) 
(7.18 3.46 8.7) 
(8.16 3.83 8.93) 
(8.49 5.31 7.47) 
(7.01 4.2 11.9) 
(9.44 2.65 7.37) )

; cluster of data records labeled 3 at offset 2
(select data (K:clusters 2)) 
( (2.29 4.18 1.06) 
(1.85 1.89 0.11) 
(2.43 2.14 1.59) 
(2.48 2.26 0.19) 
(3.12 3.1 1.4) 
(1.17 4.46 1.02) 
(2.11 2.14 0.85) )

次の最後の例では、データにクラスター・ラベル(1 から 3)を追加しています:
In the last example the cluster labels (from 1 to 3) are added to the data:

; append a cluster label to each data record
(set 'labeled-data (transpose (push K:labels (transpose data) -1)))

labeled-data: 
( (6.57 4.96 11.91 2) 
(2.29 4.18 1.06 3) 
(8.63 2.51 8.11 2) 
(1.85 1.89 0.11 3) 
(7.56 7.93 5.06 1) 
(3.61 7.95 5.11 1) 
... ...
(2.11 2.14 0.85 3) 
(9.44 2.65 7.37 2) )

コードがある名前空間コンテキストで書かれる時は、結果の入るコンテキストには MAIN を先付けすべきです。 そのコンテキストが存在しない場合は、生成されます。
The result context should be prefixed with MAIN when code is written in a namespace context. If the context does not exists already, it will be created.

先に kmeans-train を走らせ、K:labelsK:clustersK:centroidsK:deviations の結果がすでに存在していても、上書きされます。
Results in K:labels, K:clusters, K:centroids and K:deviations will be overwritten, if already present from previous runs of kmeans-train.



lambda

lambda の省略形である fn の説明を見てください。
See the description of fn, which is a shorter form of writing lambda.



lambda-macro

define-macro の説明を見てください。
See the description of define-macro.



lambda?

syntax: (lambda? exp)

exp の値がラムダ式の場合のみ true を返し、それ以外では nil を返します。
Returns true only if the value of exp is a lambda expression; otherwise, returns nil.

(define (square x) (* x x))  (lambda (x) (* x x))

square  (lambda (x) (* x x))

(lambda? square)   true

lambda 式についてのさらなる情報は、definedefine-macro を見てください。
See define and define-macro for more information about lambda expressions.



last utf8

syntax: (last list)
syntax: (last array)
syntax: (last str)

リストや文字列の最後の要素を返します。(訳注:Common Lisp の last は最後の要素をリストで返しますが、newLISP の last は要素のみを返します。)
Returns the last element of a list or a string.

(last '(1 2 3 4 5))   5
(last '(a b (c d)))   (c d)

(set 'A (array 3 2 (sequence 1 6)))
 ((1 2) (3 4) (5 6))
(last A)              (5 6)

(last '())            ERR: list is empty
(訳注:最後の行は、Common Lispではエラーにならず nil が返ります。)

第二形式では、文字列 str の最後の文字が文字列で返されます。
In the second version the last character in the string str is returned as a string.

(last "newLISP")   "P"

UTF-8 版の newLISP では、last はバイト境界ではなく、キャラクタ境界で動作します。 firstrestnth も見てください。
Note that last works on character boundaries rather than byte boundaries when the UTF-8–enabled version of newLISP is used. See also first, rest and nth.



last-error

syntax: (last-error)
syntax: (last-error int-error)

シンタックス・エラーやリソースの枯渇に起因する newLISP で生じた最後のエラーを報告します。 起こりうる全てのエラーのまとめは、付録の エラー コード の章を見てください。
Reports the last error generated by newLISP due to syntax errors or exhaustion of some resource. For a summary of all possible errors see the chapter Error codes in the appendix.

newLISPセッションが始まってから一度もエラーが起こらなければ、nil が返ります。
If no error has occurred since the newLISP session was started, nil is returned.

int-error が指定されると、その番号とエラー・テキストのリストが返ります。
When int-error is specified, a list of the number and the error text is returned.

(last-error)   nil

(abc)

ERR: invalid function : (abc)

(last-error)  (24 "ERR: invalid function : (abc)")

(last-error 24)  (24 "invalid function")
(last-error 1)  (1 "not enough memory")
(last-error 12345)  (12345 "Unknown error")

エラー番号の範囲外では、"Unknown error" がエラー・テキストとして与えられます。
For error numbers out of range the string "Unknown error" is given for the error text.

エラーは、error-event とユーザ定義エラー・ハンドラで捕まえることができます。
Errors can be trapped by error-event and user defined error handlers.

ネットワークの条件によって発生するエラー用の net-error やオペレーティング・システムによって発生するエラー用の sys-error も見てください。
See also net-error for errors generated by networking conditions and sys-error for errors generated by the operating system.



legal?

syntax: (legal? str)

str の語句が newLISP シンボルとして適正かどうかを確かめます。 関数 sym を使えば、適正でないシンボルをることが可能です(例えば、スペースやクォートを含むシンボルとか、その他、通常許可されない文字とか)。 連想データ・アクセスにそれらを使う時、非適正シンボルがよく生成されます。
The token in str is verified as a legal newLISP symbol. Non-legal symbols can be created using the sym function (e.g. symbols containing spaces, quotes, or other characters not normally allowed). Non-legal symbols are created frequently when using them for associative data access:

(symbol? (sym "one two"))   true

(legal? "one two")          nil  ; contains a space

(set (sym "one two") 123)   123

(eval (sym "one two"))      123

この例は、文字列 "one two" からシンボルが生成されて変数のように扱えたとしても、適正なシンボルとならない事を示しています。
The example shows that the string "one two" does not contain a legal symbol although a symbol can be created from this string and treated like a variable.



length  bigint

syntax: (length exp)

リストの要素数、アレイの行数、文字列やシンボル名のバイト数を返します。
Returns the number of elements in a list, the number of rows in an array and the number of bytes in a string or in a symbol name.

length を数値に適用した場合、整数や大整数では桁数を返します。 浮動小数点では小数点より前の桁数(訳注:つまり、整数部の桁数)を返します。
Applied to a number, length returns the number of digits for normal and big integers and the number of digits before the decimal separator for floats.

(訳注:上記以外の)他の型では、length0 を返します。
length returns 0 on all other types.

バージョン 10.5.6 以前の length は、整数 (4 か 8) 、浮動小数点 (8) のように格納サイズをバイト数で返していました。
Before version 10.5.6 length returned the storage size in bytes for integers (4 or 8) and floats (8).

; number of top level elements in a list
(length '(a b (c d) e))          4
(length '())                     0
(set 'someList '(q w e r t y))   (q w e r t y)
(length someList)                6

; number of top level elements in an array
(set 'ary (array 2 4 '(0)))   ((1 2 3 4) (5 6 7 8))
(length ary)                  2

; number of bytes in a string or byte buffer
(length "Hello World")   11
(length "")              0
(length "\000\001\003")  3

; number of bytes in a symbol name string
(length 'someVar)   7

; number of int digits in a number
(length 0)          0
(length 123)        3
(length 1.23)       1
(length 1234567890123456789012345L)  25 

UTF-8 の文字数計算には utf8len を使ってください。
Use utf8len to calculate the number of UTF-8 characters in a string.



let

syntax: (let ((sym1 [exp-init1]) [(sym2 [exp-init2]) ... ]) body)
syntax: (let (sym1 exp-init1 [sym2 exp-init2 ... ]) body)

一個以上の変数 sym1, sym2, ... が、exp-init1, exp-init2, ... を初期値としてローカルに宣言されます。 完全に括弧で括られた第一構文では初期値がオプションとなり、見つからない場合は nil になります。
One or more variables sym1, sym2, ... are declared locally and initialized with expressions in exp-init1, exp-init2, etc. In the fully parenthesized first syntax, initializers are optional and assumed nil if missing.

ローカル変数が初期化される時、初期化式は let 宣言文より前に束縛されたシンボルを使って評価されます。(訳注:つまり、let で初期化中の評価で束縛されたシンボルは使われません。そのため、) let の初期化中の評価で束縛されたシンボルを順次使いたい時は、letn を使ってください。
When the local variables are initialized, the initializer expressions evaluate using symbol bindings as before the let statement. To incrementally use symbol bindings as evaluated during the initialization of locals in let, use letn.

exp-body の一個以上の式がローカルに定義された sym1, sym2 他を使って評価されます。 let は使われる場所が閉じているローカル変数を定義するので、複雑な式を分解するために役立ちます。 第二形式は機能的に変わらずに、変数式対周りの括弧を省略できます。
One or more expressions in exp-body are evaluated using the local definitions of sym1, sym2 etc. let is useful for breaking up complex expressions by defining local variables close to the place where they are used. The second form omits the parentheses around the variable expression pairs but functions identically.

(define (sum-sq a b)
    (let ((x (* a a)) (y (* b b)))
        (+ x y)))

(sum-sq 3 4)  25

(define (sum-sq a b)           ; alternative syntax
    (let (x (* a a) y (* b b))
        (+ x y)))

変数 xy が初期化されてから、式 (+ x y) が評価されます。 この let 形式は本当に効率的な形で、書くのが楽になる構文です:
The variables x and y are initialized, then the expression (+ x y) is evaluated. The let form is just an optimized version and syntactic convenience for writing:

((lambda (sym1 [sym2 ... ]) exp-body ) exp-init1 [ exp-init2 ])

入れ子構造的 let 用の letnnil に初期化する local も見てください。 local は変数を自動的に nil に初期化します。
See also letn for an incremental or nested form of let and local for initializing to nil. See local for automatic initialization of variables to nil.

(訳例:
> (let ((x) (y) (z)) (setq x 1 y 2 z 3) (list x y z))
(1 2 3)
> (list x y z)
(nil nil nil)
> (let (x y z) (println (list x y z))(setq x 1 y 2 z 3) (list x y z))
(nil nil nil)
(1 2 3)
> (list x y z)
(nil 2 nil)
> 
第二形式 の let で、変数を全て nil にしようとして二番目の例のように記述すると、不用意に(上記、y のような)グローバル変数を作ってしまいますので、ご注意を。(私だけかもしれませんが、、、汗)
> (local (x y z) (println (list x y z))(setq x 1 y 2 z 3) (list x y z))
(nil nil nil)
(1 2 3)
> (list x y z)
(nil nil nil)
> 
全て nil で初期化したい場合は、このように local が便利です。)


letex

syntax: (letex ((sym1 [exp-init1]) [(sym2 [exp-init2]) ... ]) body)
syntax: (letex (sym1 exp-init1 [sym2 exp-init2 ... ]) body)

この関数は、let と ローカル変数を評価する前に式に展開する expand との組み合わせです。 完全に括弧で括られた第一構文では初期値はオプションとなり、見つからない場合は nil になります。
This function combines let and expand to expand local variables into an expression before evaluating it. In the fully parenthesized first syntax initializers are optional and assumed nil if missing.

どちらの形式も機能的には同じですが、第二形式では(訳注:let と同じように)初期化周りの括弧が省略できます:
Both forms provide the same functionality, but in the second form the parentheses around the initializers can be omitted:

(letex (x 1 y 2 z 3) '(x y z))     (1 2 3)

(letex ( (x 1) (y '(a b c)) (z "hello") ) '(x y z)) 

 (1 (a b c) "hello")

'(x y z) が評価を得る前に、xyzletex の初期化リストの初期値で文字通り置き換えられます。 最終的に評価を得る式は '(1 2 3) となります。
Before the expression '(x y z) gets evaluated, x, y and z are literally replaced with the initializers from the letex initializer list. The final expression which gets evaluated is '(1 2 3).

(訳例:
> (let (x 1 y 2 z 3) (print (list x y z)) '(x y z))
(1 2 3)(x y z)
> (letex (x 1 y 2 z 3) (print (list x y z)) '(x y z))
(1 2 3)(1 2 3)
> (let ( (x 1) (y '(a b c)) (z "hello") ) (print (list x y z))'(x y z))
(1 (a b c) "hello")(x y z)
> (letex ( (x 1) (y '(a b c)) (z "hello") ) (print (list x y z))'(x y z))

ERR: invalid function in function list : (a b c)
> 
このように、 let では、x、y、z に 1、2、3 が代入されるのに対して、 letex では、文字通り置き換わります。
置き換わる式は、評価された初期値です。そのため、
> (let ( (x 1) (y '(a b c)) (z "hello") ) (print (list x y z))'(x y z))
(1 (a b c) "hello")(x y z)
> (letex ( (x 1) (y '(a b c)) (z "hello") ) (print (list x y z))'(x y z))

ERR: invalid function in function list : (a b c)
> (letex ( (x 1) (y '(a b c)) (z "hello") ) (print (list x 'y z))'(x y z))
(1 (a b c) "hello")(1 (a b c) "hello")
> 
使い方によっては、この例の y のように先付けのクォートが必要なこともあります。)

二番目の例として、加算関数を作る関数 make-adder を定義します:
In the second example a function make-adder is defined for making adder functions:

(define (make-adder n)
    (letex (c n) (lambda (x) (+ x c))))

(define add3 (make-adder 3))  (lambda (x) (+ x 3))

(add3 10)  13

; letex can expand symbols into themselves
; the following form also works

(define (make-adder n)
     (letex (n n) (lambda (x) (+ x n))))

letexn を定数 3 に評価して、ラムダ式内の c と置き換えます。二番目の例では、letex で同じ変数名で行うやり方を示しています。(訳注:言うまでもありませんが、letletn では、ラムダ式内の変数を置き換えることはできません。)
letex evaluates n to the constant 3 and replaces c with it in the lambda expression. The second examples shows, how a letex variable can be expanded into itself.



letn

syntax: (letn ((sym1 [exp-init1]) [(sym2 [exp-init2]) ... ]) body)
syntax: (letn (sym1 exp-init1 [sym2 exp-init2 ... ]) body)

letn は、入れ子になった let とも考えられ、let の様に動作します。 しかし、let を入れ子にしていったように、初期化式を評価する時、新たなシンボル束縛を順次使っていきます。 完全に括弧で括られる第一構文では初期値はオプションとなり、見つからない場合は nil になります。
letn is like a nested let and works similarly to let, but will incrementally use the new symbol bindings when evaluating the initializer expressions as if several let were nested. In the fully parenthesized first syntax, initializers are optional and assumed nil if missing.

次の letletn の比較が、その違いを示しています:
The following comparison of let and letn show the difference:

(set 'x 10)
(let ((x 1) (y (+ x 1))) 
(list x y))            (1 11)

(letn ((x 1) (y (+ x 1))) 
(list x y))           (1 2)

let を使っている最初の例で、変数 ylet 式より前に束縛された x を使って計算されます。 letn を使った二番目の例で、変数 y は新たにローカルで束縛された x を使って計算されます。
While in the first example using let the variable y is calculated using the binding of x before the let expression, in the second example using letn the variable y is calculated using the new local binding of x.

(letn  (x 1 y x) 
    (+ x y))       2

;; same as nested let's

(let (x 1)
    (let (y x)
      (+ x y)))    2

letn は、入れ子になった let の様に動作します。 初期化周りの括弧は、省略できます。
letn works like several nested let. The parentheses around the initializer expressions can be omitted.



list

syntax: (list exp-1 [exp-2 ... ])

exp が評価され、その値が新しいリストを構成するために使われます。 アレイ型の引数は、リスト型に変換されますので注意してください。 多次元リストを処理する際はアレイの章も見てください。
The exp are evaluated and the values used to construct a new list. Note that arguments of array type are converted to lists. See the chapter Arrays for dealing with multidimensional lists.

(list 1 2 3 4 5)                 (1 2 3 4 5)
(list 'a '(b c) (+ 3 4) '() '*)  (a (b c) 7 () *)

リストに束縛する他の形式として conspush も見てください。
See also cons and push for other forms of building lists.



list?

syntax: (list? exp)

exp の値がリストの時のみ true が返り、それ以外では nil が返ります。 ラムダ式やラムダ-マクロ式もリスト式の特殊な形として認識されることに注意してください。
Returns true only if the value of exp is a list; otherwise returns nil. Note that lambda and lambda-macro expressions are also recognized as special instances of a list expression.

(set 'var '(1 2 3 4))     (1 2 3 4)
(list? var)               true

(define (double x) (+ x x))

(list? double)            true


load

syntax: (load str-file-name-1 [str-file-name-2 ... ] [sym-context])

一個以上の str-file-name で指定されるソール・ファイルをロードして newLISP に翻訳し、そのファイルに含まれる式群を評価します。 ロードに成功すると、load は最後のファイルの最後の式の結果を返し、ロードできなかった時はエラーを起こします。
Loads and translates newLISP from a source file specified in one or more str-file-name and evaluates the expressions contained in the file(s). When loading is successful, load returns the result of the last expression in the last file evaluated. If a file cannot be loaded, load throws an error.

ロードしているファイル内にコンテキスト切り替えが存在しない限り、評価のコンテキスト用にオプションの sym-context が指定できます。 context 切り替えを含んでいないファイルは、デフォルトで MAIN コンテキストにロードされます。
An optional sym-context can be specified, which becomes the context of evaluation, unless such a context switch is already present in the file being loaded. By default, files which do not contain context switches will be loaded into the MAIN context.

str-file-name の種類には URL も含まれます。 http:// file:// のどちらの URL もサポートされます。
The str-file-name specs can contain URLs. Both http:// and file:// URLs are supported.

(load "myfile.lsp")    

(load "a-file.lsp" "b-file.lsp") 

(load "file.lsp" "http://mysite.org/mypro")

(load "http://192.168.0.21:6000//home/test/program.lsp")

(load "a-file.lsp" "b-file.lsp" 'MyCTX)

(load "file:///usr/local/share/newlisp/mysql.lsp")

load 中に評価される式が context を変える場合でも、load を実行しているプログラミング・モジュールに影響を与えません。
In case expressions evaluated during the load are changing the context, this will not influence the programming module doing the load.

load 後の現在のコンテキストは、load 前と常に同じです。
The current context after the load statement will always be the same as before the load.

通常のファイルの たぐいと URL は、同じロード・コマンド内に混在可能です。
Normal file specs and URLs can be mixed in the same load command.

HTTP URL の load は、Unix ライクなオペレーティングシステムで走っている newLISP サーバーからリモートでコードをロードするためにも使えます。 このモードで、load は目標とする URL に HTTP GET 要求リクエストを出します。 パス名がルート・ディレクトリから相対的に指定されている時、二つのバックスラッシュが要求されることに気を付けてください。 HTTP モードの load は、60秒のタイムアウトを見ます。
load with HTTP URLs can also be used to load code remotely from newLISP server nodes running on a Unix-like operating system. In this mode, load will issue an HTTP GET request to the target URL. Note that a double backslash is required when path names are specified relative to the root directory. load in HTTP mode will observe a 60-second timeout.

最後から二つ目の行は、ファイルをコンテキスト MyCTX にロードします。 クォートは、そのコンテキストが存在しない時の生成を促します。
The second to last line causes the files to be loaded into the context MyCTX. The quote forces the context to be created if it did not exist.

file:// URL は、三つ目の / の後にディレクトリの詳細を続けます。
The file:// URL is followed by a third / for the directory spec.



local

syntax: (local (sym-1 [sym-2 ... ]) body)

一個以上のシンボル sym-1–nil に初期化し、body の式群を評価します。
Initializes one or more symbols in sym-1— to nil, evaluates the expressions in body, and returns the result of the last evaluation.

local は let の様に動作しますが、ローカル変数は全て nil に初期化されます。
local works similarly to let, but local variables are all initialized to nil.

local は、明示的な初期化無しにローカル変数を提供する簡単な方法です。
local provides a simple way to localize variables without explicit initialization.



log

syntax: (log num)
syntax: (log num num-base)

第一構文では、num の式が評価され、その結果から自然対数を計算します。
In the first syntax, the expression in num is evaluated and the natural logarithmic function is calculated from the result.

(log 1)          0
(log (exp 1))    1

第二構文では、任意の底として num-base を指定できます。
In the second syntax, an arbitrary base can be specified in num-base.

(log 1024 2)              10
(log (exp 1) (exp 1))      1

e (2.718281828) を底とする log の逆関数 exp も見てください。
See also exp, which is the inverse function to log with base e (2.718281828).



lookup

syntax: (lookup exp-key list-assoc [int-index [exp-default]])

連想リスト list-assoc 中から exp-key と同じ値を持つキー要素を見つけ、その連想の int-index の要素を返します(int-index がない場合は、最後の要素) 。
Finds in list-assoc an association, the key element of which has the same value as exp-key, and returns the int-index element of association (or the last element if int-index is absent).

exp-key に一致する連想が見つからなかった時に返す exp-default を、オプションで指定できます。 exp-default がなくて、連想が見つからなかった時は nil が返ります。
Optionally, exp-default can be specified, which is returned if an association matching exp-key cannot be found. If the exp-default is absent and no association has been found, nil is returned.

文字列、リスト、アレイの要素指定 も見てください。
See also Indexing elements of strings and lists.

lookupassoc に似ていますが、見つかったリストから要素を指定して取り出す手間が省けます。
lookup is similar to assoc but goes one step further by extracting a specific element found in the list.

(set 'params '(
    (name "John Doe") 
    (age 35) 
    (gender "M") 
    (balance 12.34)
))

(lookup 'age params)              35

; use together with setf to modify and association list
(setf (lookup 'age params) 42)    42
(lookup 'age params)              42

(set 'persons '(
    ("John Doe" 35 "M" 12.34) 
    ("Mickey Mouse" 65 "N" 12345678)
))

(lookup "Mickey Mouse" persons 2)     "N"
(lookup "Mickey Mouse" persons -3)    65
(lookup "John Doe" persons 1)         35 
(lookup "John Doe" persons -2)        "M"

(lookup "Jane Doe" persons 1 "N/A")   "N/A"

assoc も見てください。
See also assoc



lower-case utf8

syntax: (lower-case str)

文字列 str 中の文字を小文字に変換します。 新しい文字列が作られ、オリジナルは変わずに残ります。
Converts the characters of the string in str to lowercase. A new string is created, and the original is left unaltered.

(lower-case "HELLO WORLD")   "hello world"
(set 'Str "ABC")
(lower-case Str)   "abc"
Str                "ABC"

関数 upper-casetitle-case も見てください。
See also the upper-case and title-case functions.



macro

syntax: (macro (sym-name [sym-param-1 ... ]) [body-1 ... ])

この関数 macro は拡張マクロ(訳注:macro)の定義に使います。 macro の構文は define-macro の構文と同一です。 けれども、define がランタイム中に評価される関数を定義するのに対して、macro はソースのロード時や読み込み処理中に使われる fexpr 関数(訳注: fexpr とは、オペランドが評価されずに渡される関数)を定義して、特定の式が呼び出された時にそれを異なる形に変換します。
The macro function is used to define expansion macros. The syntax of macro is identical to the syntax of define-macro. But while define-macro defines are fexprs functions to be evaluated at run-time, macro defines a function to be used during the source loading and reading process to transform certain expression call patterns into different call patterns.

(macro (double X) (+ X X))  (lambda-macro (X) (expand '(+ X X)))

(double 123)  246

シンボル呼び出し形式に定義された macro は、全て、読み出し時の内部処理で expand 式を使って翻訳されます。 この様子を、read-expr 関数を使って見ることができます:
Internally all macro defined symbol call patterns are translated using the expand expression during source reading. This can be shown using the read-expr function:

(read-expr "(double 123)")  (+ 123 123)

展開される変数名は全て大文字で始まらなければなりません。 macro の中に他の macro 定義を入れ子することができます。 しかしながら、同一 newLISP セッション内では macro による定義を同じシンボルに何度も繰り返し適用することはできません。 マクロを再定義したい場合(例えば、macro で定義された存在を別の定義でソース読み込みに使いたい時)は、下記のように関数 constant を使ってください:
All variable names to be expanded must start in upper-case. Macros can be nested containing other macros defined earlier. But macro definitions cannot be repeated for the same symbol during the same newLISP session. To redefine a macro, e.g. for reading source with a different definition of an exisiting macro definition, use the constant function in the following way:

; change existing macro 'double' to allow floating point parameters
; use upper-case for variables for expansion

(constant 'double (lambda-macro (X) (expand '(add X X))))
 (lambda-macro (X) (expand '(add X X)))

(double 1.23)  2.46

constantmacro の再定義に使えるだけで、新 macro の生成にも使えないことに注意してください。 newLISP 内部処理において、シンボルに定義された macro はソースの読み込み時に実行されますが、評価はしません。
Note, that constant can be used only to re-define macros, not to create new macros. Internally newLISP knows that macro defined symbols are executed during source reading, not evaluation.

再定義は、新たに読み込まれるコードにのみ影響を与えます。既にロードされたコードやリーダー・ルーチンで翻訳されたコードには影響を与えません。、
The redefinition will only affect future read code, it will not affect code already load and translated by the reader routines.

Using map and apply with macromapapply での macro の使用)

macromapapply を使うと、拡張関数が展開されます:
When mapping macros using map or apply the expansion function is mapped:

> (macro (double X) (+ X X))
(lambda-macro (X) (expand '(+ X X)))

> (map double '(1 2 3 4 5))
((+ 1 1) (+ 2 2) (+ 3 3) (+ 4 4) (+ 5 5))

> (map eval (map double '(1 2 3 4 5)))
(2 4 6 8 10)

> (apply double '(10))
(+ 10 10)
>

macro での定義がソース読み込み時にどのように動作するかを、この様子が教えてくれます。
This is useful to find out how the expansion mechanism of our macro definition works during source load time.

Differences between macro and define-macro and potential problems.(macrodefine-macro との相違点、及び潜在する問題点)

macro による定義は、define-macro で作られる fexpr に存在する変数補足 に対して、耐性があります。
macro definitions are not susceptible to variable capture as are fexprs made with define-macro:

(define-macro (fexpr-add A B) 
    (+ (eval A) (eval B)))

(macro (mac-add A B) 
    (+ A B))

(set 'A 11 'B 22)

; variable capture when using the same symbols 
; used as locals in define-macro for callling

(fexpr-add A B) 
; or
(fexpr-add B A) 
ERR: value expected : A
called from user defined function fexpr-add

; no variable capture when doing the same with 
; expansion macros

(mac-add A B)  33

(mac-add B A)  33

とは言え、macro を使った拡張マクロにも、define-macro の時のような望んではいない二重評価が存在します:
But expansion macros using macro are susceptible to unwanted double evaluation, just like define-macro is:

(define-macro (fexpr-double X) 
    (+ (eval X) (eval X)))

(macro (mac-double X) 
    (+ X X))

(set 'a 10)
(fexpr-double (inc a))  23 ; not 22 as expected

(set 'a 10)
(mac-double (inc a))  23 ; not 22 as expected

どちらの場合も、内包する (inc a) 式が二回評価されています。 macro 式や define-macro 式を書く時は、このことを考量しておく必要があります。
In both cases the incoming expression (inc a) gets evaulated twice. This must be considered when writing both, macro or define-macro expressions and symbols occur more than once in the body of the definition.

ソース・コード読み取り中に式を一般処理する reader-event も見てください。
See also reader-event for general preprocessing of expressions during reading of source code.



macro?

syntax: (macro? exp)

exp がラムダ・マクロ式に評価される時に true を返し、それ以外では nil を返します。
Returns true if exp evaluates to a lambda-macro expression; otherwise, nil is returned.

(define-macro (mysetq lv rv) (set lv (eval rv)))

(macro? mysetq)   true

(macro (my-setq Lv Rv) (set 'Lv Rv))

(macro? my-setq)  true


main-args

syntax: (main-args)
syntax: (main-args int-index)

main-args は、プログラムの実行名とコマンド・ラインの引数を各々文字列にしたものをメンバーとするリストを返します。
main-args returns a list with several string members, one for program invocation and one for each of the command-line arguments.

newlisp 1 2 3

> (main-args)
("/usr/local/bin/newlisp" "1" "2" "3")

コマンド・プロンプトで newlisp 1 2 3 が実行された後、main-args は実施プログラム名とコマンド・ラインの引数の入ったリストを返します。
After newlisp 1 2 3 is executed at the command prompt, main-args returns a list containing the name of the invoking program and three command-line arguments.

main-args はオプションで、リストの要素指定用 int-index を取ることができます。 要素位置が範囲外なら、戻り値はリストの最後の要素ではなく、リストの要素指定のように nil になることに注意してください。
Optionally, main-args can take an int-index for indexing into the list. Note that an index out of range will cause nil to be returned, not the last element of the list like in list-indexing.

newlisp a b c

> (main-args 0)   
"/usr/local/bin/newlisp"
> (main-args -1)  
"c"
> (main-args 2)   
"b"
> (main-args 10)
nil

newLISP がスクリプトから実行される場合は、main-args がスクリプトの 名前も二番目の引数として返すことに注意してください:
Note that when newLISP is executed from a script, main-args also returns the name of the script as the second argument:

#!/usr/local/bin/newlisp
# 
# script to show the effect of 'main-args' in script file

(print (main-args) "\n")
(exit)

# end of script file

;; execute script in the OS shell:

script 1 2 3

("/usr/local/bin/newlisp" "./script" "1" "2" "3")

このスクリプトを異なるコマンド・ライン・パラメータで試してみてください。
Try executing this script with different command-line parameters.



make-dir

syntax: (make-dir str-dir-name [int-mode])

str-dir-name で指定されたディレクトリをオプションのアクセス・モード int-mode で作ります。 結果次第で truenil が返ります。 アクセス・モードの指定がなければ、ほとんどの Unix システムでは drwxr-xr-x がデフォルトです。
Creates a directory as specified in str-dir-name, with the optional access mode int-mode. Returns true or nil depending on the outcome. If no access mode is specified, most Unix systems default to drwxr-xr-x.

Unix システム上で指定されるアクセス・モードは、OS の user-mask による設定でシステム管理者によってもマスクされます。 Unixシステム上での user-mask は、umaskコマンドを使って取り出せ、 通常、ファイルの所有者以外の書き込み(と生成)許可をマスクする 0022(8進数)となっています。
On Unix systems, the access mode specified will also be masked by the OS's user-mask set by the system administrator. The user-mask can be retrieved on Unix systems using the command umask and is usually 0022 (octal), which masks write (and creation) permission for non-owners of the file.

;; 0 (zero) in front of 750 makes it an octal number

(make-dir "adir" 0750)  

この例では、カレント・ディレクトリに adir という名前のディレクトリを 0750(8進数 750 = drwxr-x---)のアクセス・モードで作っています。
This example creates a directory named adir in the current directory with an access mode of 0750 (octal 750 = drwxr-x---).



map

syntax: (map exp-functor list-args-1 [list-args-2 ... ])

組込関数か(訳注:ユーザ)定義関数かラムダ式の exp-functorlist-args-1, list-args-2–– で指定される引数に連続的に適用し、結果の全てをリストにして返します。 バージョン 10.5.5 からは、list-args にベクトル・アレイも使えますが、返り値はリストになります。
Successively applies the primitive function, defined function, or lambda expression exp-functor to the arguments specified in list-args-1 list-args-2—, returning all results in a list. Since version 10.5.5 list-args can also be array vectors, but the returned result will always be a list.

(map + '(1 2 3) '(50 60 70))   (51 62 73)

(map if '(true nil true nil true) '(1 2 3 4 5) '(6 7 8 9 10))
 '(1 7 3 9 5)

(map (fn (x y) (* x y)) '(3 4) '(20 10))
 (60 40)

次の例が示しているのは、map 用の関数を動的に生成する方法です:
The second example shows how to dynamically create a function for map:

(define (foo op p) 
    (append (lambda (x)) (list (list op p 'x))))

短縮形の fn も使えます:
We can also use the shorter fn:

(define (foo op p) 
    (append (fn (x)) (list (list op p 'x))))

これで foo が関数生成器のように動作します:
foo now works like a function-maker:

(foo 'add 2)   (lambda (x) (add 2 x))

(map (foo add 2) '(1 2 3 4 5))   (3 4 5 6 7)

(map (foo mul 3) '(1 2 3 4 5))   (3 6 9 12 15)

オペランドの前のクォートを省略できることに着目してください。 というのも、newLISP の組込はそれ自身に評価されるからです。 (訳注:ユーザ定義関数でも、クォートは省略できます。)
Note that the quote before the operand can be omitted because primitives evaluate to themselves in newLISP.

map を関数定義と組み合わせると、次のようなことが可能です:
By incorporating map into the function definition, we can do the following:

(define (list-map op p lst) 
    (map (lambda (x) (op p x)) lst))

(list-map + 2 '(1 2 3 4))   (3 4 5 6)

(list-map mul 1.5 '(1 2 3 4))   (1.5 3 4.5 6)

map には内部リスト・インデックス値 $idx も配置できます。
map also sets the internal list index $idx.

(map (fn (x) (list $idx x)) '(a b c))  ((0 a) (1 b) (2 c))

使われる引数の数は第一引数のリストの長さで決まります。 残りのリストで引数が見つからない時、map はその引数の段階でパラメータ収集を止めます。 これは、置換中の n 番目のパラメータ・リストが、n 番目の行に変換されることを確実にします。 引数リストが多くの要素を含んでも、余分な要素は無視されます。

(訳例:
> (map (fn (x y z) (list $idx x y z)) '(a b c) '(1 2) '(A B C D E))
((0 a 1 A) (1 b 2 B) (2 c nil nil))
> 

The number of arguments used is determined by the length of the first argument list. Arguments missing in other argument lists cause map to stop collecting parameters for that level of arguments. This ensures that the nth parameter list gets converted to the nth column during the transposition occurring. If an argument list contains too many elements, the extra ones will be ignored.

構文に括弧を使うような特殊形式(例えば caseとか)は、 map に使えません。
Special forms which use parentheses as syntax cannot be mapped (i.e. case).



mat

syntax: (mat + | - | * | / matrix-A matrix-B)
syntax: (mat + | - | * | / matrix-A number)

この関数を第一構文で使うと、matrix-Amatrix-B の二次元行列に対して、高速浮動小数点スカラ演算を実行します。 演算の型には、四つの数値演算子 +, -, *, / の中から一つを指定します。 newLISP では、通常これら数値演算子型は整数演算に使われますが、mat ではこれらの演算子全てが浮動小数点演算 (add, sub, mul, div) を実行します。
Using the first syntax, this function performs fast floating point scalar operations on two-dimensional matrices in matrix-A or matrix-B. The type of operation is specified by one of the four arithmetic operators +, -, *, or /. This type of arithmetic operator is typically used for integer operations in newLISP. In the case of mat, however, all operations will be performed as floating point operations (add, sub, mul, div).

newLISP における行列は二次元のリストかアレイです。 newLISP はリストとアレイを内部的に高速アクセス可能な C 言語データ・オブジェクトに変換します。 このことが newLISP での行列演算を高速にしていて、C で直接コード化したものと同じくらいです。 同じことが、行列演算 multiplyinvert にも言えます。
Matrices in newLISP are two-dimensional lists or arrays. Internally, newLISP translates lists and arrays into fast, accessible C-language data objects. This makes matrix operations in newLISP as fast as those coded directly in C. The same is true for the matrix operations multiply and invert.

(set 'A '((1 2 3) (4 5 6)))
(set 'B A)

(mat + A B)     ((2 4 6) (8 10 12))
(mat - A B)     ((0 0 0) (0 0 0))
(mat * A B)     ((1 4 9) (16 25 36))
(mat / A B)     ((1 1 1) (1 1 1))

; specify the operator in a variable

(set 'op +)
(mat op A B)     ((2 4 6) (8 10 12)) 

第二構文を使うと、matrix-A の全てのセルが number のスカラ値で処理されます:
Using the second syntax, all cells in matrix-A are operated on with a scalar in number:

(mat + A 5)     ((6 7 8) (9 10 11))
(mat - A 2)     ((-1 0 1) (2 3 4))
(mat * A 3)     ((3 6 9) (12 15 18))
(mat / A 10)    ((.1 .2 .3) (.4 .5 .6))

他の行列演算 detinvertmultiplytranspose も見てください。
See also the other matrix operations det, invert, multiply, and transpose.



match

syntax: (match list-pattern list-match [bool])

list-pattern のパターンを list-match のリストに対して合致判定し、合致した式をリストで返します。 list-pattern には、三つのワイルド・カード文字 ?, +, * が 使われます。
The pattern in list-pattern is matched against the list in list-match, and the matching expressions are returned in a list. The three wildcard characters ?, +, and * can be used in list-pattern.

ワイルド・カード文字は入れ子が可能です。 match は合致した式のリストを返します。 各 ?(疑問符)に対しては、合致している式要素が返ります。 各 + (プラス符号) または *(アスタリスク)に対しては、合致した要素からなるリストが返ります。 パターンが list-match のリストに対して合致しなかった時、matchnil を返します。 ワイルド・カード文字がパターンに無い時は、空リストが返ります。
Wildcard characters may be nested. match returns a list of matched expressions. For each ? (question mark), a matching expression element is returned. For each + (plus sign) or * (asterisk), a list containing the matched elements is returned. If the pattern cannot be matched against the list in list-match, match returns nil. If no wildcard characters are present in the pattern an empty list is returned.

第三引数はオプションで、論理値 true (あるいは、nil 以外に評価される式) を与えることができます。 これにより、(訳注:合致した時の)match の戻り値が(訳注:list-match の)全要素になります。
Optionally, the Boolean value true (or any other expression not evaluating to nil) can be supplied as a third argument. This causes match to show all elements in the returned result.

findrefref-allreplace において、 match はファンクタ(関数オブジェクト)のパラメータとして使われます。 また、リストに対する find-all の内部で使われます。
match is frequently employed as a functor parameter in find, ref, ref-all and replace and is internally used by find-all for lists.

(match '(a ? c) '(a b c))   (b)

(match '(a ? ?) '(a b c))   (b c)

(match '(a ? c) '(a (x y z) c))   ((x y z))

(match '(a ? c) '(a (x y z) c) true)   (a (x y z) c)

(match '(a ? c) '(a x y z c))   nil


(match '(a * c) '(a x y z c))   ((x y z))

(match '(a (b c ?) x y z) '(a (b c d) x y z))   (d)

(match '(a (*) x ? z) '(a (b c d) x y z))   ((b c d) y)


(match '(+) '())   nil

(match '(+) '(a))   ((a))

(match '(+) '(a b))   ((a b))

(match '(a (*) x ? z) '(a () x y z))   (() y)

(match '(a (+) x ? z) '(a () x y z))   nil 

match における * 演算子は、可能な限り少ない要素を捕まえようとしますが、合致しないとバックトラックして、より多くの要素を捕まえようとするので注意してください。
Note that the * operator tries to grab the fewest number of elements possible, but match backtracks and grabs more elements if a match cannot be found.

+* と似た動作をしますが、少なくとも一つのリスト要素を必要とします。
The + operator works similarly to the * operator, but it requires at least one list element.

次の例は、合致式が変数をどのように束縛するかを示しています。
The following example shows how the matched expressions can be bound to variables.

(map set '(x y) (match '(a (? c) d *) '(a (b c) d e f)))

x   b
y   (e f)

文字列に対して、match は使えません。 より強力な文字列合致には、regexfindfind-allparse を使ってください。
Note that match for strings has been eliminated. For more powerful string matching, use regex, find, find-all or parse.

unify は別の合致表現用関数で、PROLOG のように振る舞います。
unify is another function for matching expressions in a PROLOG like manner.



max

syntax: (max num-1 [num-2 ... ])

num-1 以下の式を評価して、最大数を返します。
Evaluates the expressions num-1— and returns the largest number.

(max 4 6 2 3.54 7.1)   7.1

関数 min も見てください。
See also the min function.



member

syntax: (member exp list)
syntax: (member str-key str [num-option])

第一構文の member は、リスト list で要素 exp を検索します。 要素がリストのメンバなら、元のリストで見つかった要素からの残りを新しいリストとして構成して、返します。 見つからなかった場合は nil が返ります。 num-option を指定された member は、正規表現検索を実行します。
In the first syntax, member searches for the element exp in the list list. If the element is a member of the list, a new list starting with the element found and the rest of the original list is constructed and returned. If nothing is found, nil is returned. When specifying num-option, member performs a regular expression search.

(set 'aList '(a b c d e f g h))   (a b c d e f g h)
(member 'd aList)                 (d e f g h)
(member 55 aList)                 nil

第二構文の member は、str 中の str-key を検索します。 str-key が見つかれば、 (str-key から始まる) str の全てが返ります。 見つからなければ、 nil が返ります。
In the second syntax, member searches for str-key in str. If str-key is found, all of str (starting with str-key) is returned. nil is returned if nothing is found.

(member "LISP" "newLISP")   "LISP"
(member "LI" "newLISP")     "LISP"
(member "" "newLISP")       "newLISP"
(member "xyz" "newLISP")    nil
(member "li" "newLISP" 1)   "LISP"

関連する関数 slicefind も見てください。
See also the related functions slice and find.



min

syntax: (min num-1 [num-2 ... ])

num-1 以下を評価して、一番小さい数値を返します。
Evaluates the expressions num-1— and returns the smallest number.

(min 4 6 2 3.54 7.1)   2

関数 max も見てください。
See also the max function.



mod

syntax: (mod num-1 num-2 [num-3 ... ])

num-1num-2 から 余りモジュラ・バリューを計算します。 つまり、mod が計算するのは、分子 num-i を 分母 num-i + 1 で割った時の残りです。 具体的には、戻り値は分子 - n * 分母 で、この時の n は分子を分母で割った商でゼロに近い方に丸めた整数です。 その結果、分子と同じ符合で、大きさが分母よりも小さくなります。
Calculates the modular value of the numbers in num-1 and num-2. mod computes the remainder from the division of the numerator num-i by the denominator num-i + 1. Specifically, the return value is numerator - n * denominator, where n is the quotient of the numerator divided by the denominator, rounded towards zero to an integer. The result has the same sign as the numerator and its magnitude is less than the magnitude of the denominator.

(mod 10.5 3.3)     0.6
(mod -10.5 3.3)   -0.6

整数に対してのみ動作させたい時は、関数 %(パーセント記号)を使ってください。
Use the % (percent sign) function when working with integers only.



mul

syntax: (mul num-1 num-2 [num-3 ... ])

num-1 以下の全てを評価し、その積を計算して返します。 mul は(訳注:整数と浮動小数点数の)混在型算術を実行しますが、常に浮動小数点数で返します。 NaN となる浮動小数点数に対しては、NaN が返ります。
Evaluates all expressions num-1—, calculating and returning the product. mul can perform mixed-type arithmetic, but it always returns floating point numbers. Any floating point calculation with NaN also returns NaN.

(mul 1 2 3 4 5 1.1)   132
(mul 0.5 0.5)         0.25


multiply

syntax: (multiply matrix-A matrix-B)

行列 matrix-Amatrix-B の行列積を返します。 matrix-Anm 列で、matrix-Bkl 列なら(mk は等しい)、結果は nl 列になります。 multiply は(訳注:整数と浮動小数点数の)混在型算術を実行しますが、整数の値があったとしても、結果は常に倍精度浮動小数点数です。
Returns the matrix multiplication of matrices in matrix-A and matrix-B. If matrix-A has the dimensions n by m and matrix-B the dimensions k by l (m and k must be equal), the result is an n by l matrix. multiply can perform mixed-type arithmetic, but the results are always double precision floating points, even if all input values are integers.

行列の次元は、行数と最初の行の要素数で決まります。 非正方行列で見つからない要素は、0.0 になります。 行列は、入れ子のリストでも arrayでも可能です。
The dimensions of a matrix are determined by the number of rows and the number of elements in the first row. For missing elements in non-rectangular matrices, 0.0 is assumed. A matrix can either be a nested list or array.

(set 'A '((1 2 3) (4 5 6)))
(set 'B '((1 2) (1 2) (1 2)))
(multiply A B)   ((6 12) (15 30))

(set 'v '(10 20 30))
(multiply A (transpose (list v)))  ((140) (320))

行列と n 要素のベクトル積をとる時、ベクトルは transpose を使って n1 列の行列に変換しておく必要があります。
When multiplying a matrix with a vector of n elements, the vector must be transformed into n rows by 1 column matrix using transpose.

ここで示す演算は全てリストに対してですが、アレイに対しても同じように実行できます。
All operations shown here on lists can be performed on arrays, as well.

行列演算子 detinvertmattranspose も見てください。
See also the matrix operations det, invert, mat and transpose.



name

この機能は推奨されません、代わりに term を使ってください。(訳注:この関数は V10.2 から使えませんので、name がシンボル名に使えます。以前のバージョンと互換性を持たせたい時は、

; make new code compatible with older newLISP versions
(when (< (sys-info -2) 10111)
(constant (global 'term) name)) 
という方法が使えます。 この例は、以前のマニュアルからの抜粋です。)
This function is deprecated, use term instead.



NaN?

syntax: (NaN? float)

浮動小数点演算の結果が NaN であるかどうかをテストします。 信頼できる浮動小数点演算は、'Not a Number' に対して NaN と呼ばれる IEEE 754 の特殊数値形式を返します。
Tests if the result of a floating point math operation is a NaN. Certain floating point operations return a special IEEE 754 number format called a NaN for 'Not a Number'.

; floating point operation on NaN yield NaN
(set 'x (sqrt -1))   NaN
(NaN? x)             true
(add x 123)          NaN
(mul x 123)          NaN

; integer operations treat NaN as zero
(+ x 123)   123
(* x 123)   0

; comparisons with NaN values yield nil
(> x 0)    nil
(<= x 0)   nil
(= x x)    nil

(set 'infinity (mul 1.0e200 1.0e200))  inf
(NaN? (sub infinity infinity))  true

NaN を伴なう全ての浮動小数点計算が NaN となることに注意してください。 つまり、NaN との比較では全て nil が返ります。自身との比較では true のはずですが、 ANSI C 使用時には not true の結果となるからです。 整数演算では、 NaN0(ゼロ)として扱われます。
Note that all floating point arithmetic operations with a NaN yield a NaN. All comparisons with NaN return nil, but true when comparing to itself. Comparison with itself, however, would result in not true when using ANSI C. Integer operations treat NaN as 0 (zero) values.

無限大の浮動小数点数値をテストする inf? も見てください。
See also inf? for testing a floating point value for infinity.



net-accept

syntax: (net-accept int-socket)

前もって待ち受け(listen)モードに置かれたソケット上の接続を受け入れます。 この接続の受信及び送信データ用に作成された新規ソケット・ハンドルが返ります。
Accepts a connection on a socket previously put into listening mode. Returns a newly created socket handle for receiving and sending data on this connection.

(set 'socket (net-listen 1234))
(net-accept socket)

Unixライクのオペレーティング・システムで 1024 より小さいポートを使うためには、newLISP がスーパーユーザ・モードで開始されなければならないことに注意してください。
Note that for ports less than 1024, newLISP must be started in superuser mode on Unix-like operating systems.

配布ソースのディレクトリ examples/ にあるファイル serverclient の例も見てください。
See also the files server and client examples in the examples/ directory of the source distribution.



net-close

syntax: (net-close int-socket [true])

関数 net-connectnet-accept で、前もって作成された int-socket のネットワーク・ソケットを閉じます。 成功すれば true を、失敗すれば nil を返します。
Closes a network socket in int-socket that was previously created by a net-connect or net-accept function. Returns true on success and nil on failure.

(net-close aSock)

オプションの true フラグは、ソケットの即時遮断を抑えて、実行中のデータ送信が終わるまで待ちます。
The optional true flag suppresses immediate shutdown of sockets by waiting for pending data transmissions to finish.



net-connect

syntax: (net-connect str-remote-host int-port [int-timeout-ms])
syntax: (net-connect str-remote-host int-port [str-mode [int-ttl]])
syntax: (net-connect str-file-path)

第一構文では、str-remote-host で指定されたリモート・ホスト・コンピュータと int-portで指定されたポートを接続します。 成功裏に接続した後はソケット・ハンドルが返り、それ以外では、nil が返ります。
In the first syntax, connects to a remote host computer specified in str-remote-host and a port specified in int-port. Returns a socket handle after having connected successfully; otherwise, returns nil.

(set 'socket (net-connect "example.com" 80))
(net-send socket "GET /\r\n\r\n")
(net-receive socket buffer 10000)
(println buffer)
(exit)

例では、HTTP GET 要求リクエストが送られ、その後にウェブ・ページが受信されます。 newLISP は、この例と同じ機能を提供する組込関数 get-url を持っていることに注意してください。
In the example a HTTP GET request is sent and subsequently a web page received. Note that newLISP has already a built-in function get-url offering the same functionality.

オプションで、タイムアウト値 int-timeout をミリ秒単位で指定できます。 タイムアウト値が無い時、関数はポートを開くために 10 秒待ちます。 タイムアウト値があれば、関数は利用できないポートからの戻りを早めたり、遅くしたりできます。 次の例は、開いているポートを探すポート・スキャナーを示します:
Optionally a timeout value int-timeout in milliseconds can be specified. Without a timeout value the function will wait up to 10 seconds for an open port. With a timeout value the function can be made to return on an unavailable port much earlier or later. The following example shows a port scanner looking for open ports:

(set 'host (main-args 2))
(println "Scanning: " host)
(for (port 1 1024)
    (if (set 'socket (net-connect host port 500))
        (println "open port: " port " " (or (net-service port "tcp") ""))
        (print port "\r"))
)

プログラムは、ドメイン名かドット表記の IP 番号どちらかのホストの文字列をシェル・コマンド・ラインから取り、1 から 1024 までの各ポートでオープンを試みます。 各オープン・ポートでは、ポート番号とサービス・ディスクリプション文字列が出力されます。 利用できるディスクリプションが無いなら、空文字列 "" が出力されます。 ポートが閉じている時、関数はシェル・ウィンドウで同一ライン上に留まり、番号を出力します。
The programs takes the host string from the shell command line as either a domain name or an IP number in dot notation then tries to open each port from 1 to 1024. For each open port the port number and the service description string is printed. If no description is available, an empty string "" is output. For closed ports the function outputs numbers in the shell window staying on the same line.

Unix では、net-connect がポートを利用できない時、タイムアウト終了前に nil を返すかもしれません。 MS Windows では、net-connectnil で失敗する際も、常にタイムアウトするまで待ちます。
On Unix net-connect may return with nil before the timeout expires, when the port is not available. On MS Windows net-connect will always wait for the timeout to expire before failing with nil.

UDP communications(UDP 通信)

第二構文では、第三パラメータとしてのオプション str-mode に、文字列 "udp" または "u" が指定でき、UDP(ユーザ・データグラム・プロトコル)通信に適したソケットを作成します。 UDP モードの net-connect はリモート・ホストへの接続を試みません が、アドレスが指定されれば、ソケットを作成し、そのリモート・アドレスに束縛します。 その後の net-send が、目標アドレスを含む UDP パケットを送信します。 net-send-to を使う時は、関数 net-connectnet-send-to のどちらかだけが、目標アドレスを提供すべきです。 つまり、片方の関数は目標アドレスとして空文字 "" を指定しなければなりません。
In the second syntax, a third parameter, the string "udp" or "u" can be specified in the optional str-mode to create a socket suited for UDP (User Datagram Protocol) communications. In UDP mode, net-connect does not try to connect to the remote host, but creates the socket and binds it to the remote address, if an address is specified. A subsequent net-send will send a UDP packet containing that target address. When using net-send-to, only one of the two functions net-connect or net-send-to should provide a target address. The other function should specify and empty string "" as the target address.

;; example server
(net-listen 4096 "226.0.0.1" "udp") → 5
(net-receive-from 5 20)

;; example client I
(net-connect "226.0.0.1" 4096 "udp") → 3
(net-send 3 "hello")

;; example client II
(net-connect "" 4096 "udp") → 3
(net-send-to "226.0.0.1" 4096 "hello" 3)

net-listennet-connect"udp" オプションが使われた時、関数 net-receivenet-receive-from の両方が使え、UDP 通信を実行します。 net-selectnet-peek が、ノン・ブロッキング状態での受信データ・チェックに使えます。
The functions net-receive and net-receive-from can both be used and will perform UDP communications when the "udp" option as been used in net-listen or net-connect. net-select and net-peek can be used to check for received data in a non-blocking fashion.

net-listen は、特定のローカル・アドレスとポートをソケットに束縛します。 net-connect が使われる時、ローカル・アドレスとポートはホスト OS のソケット・スタック関数によって選ばれます。
net-listen binds a specific local address and port to the socket. When net-connect is used, the local address and port will be picked by the socket-stack functions of the host OS.

UDP multicast communications(UDP マルチキャスト通信)

第三パラメータ str-mode"multi""m" を指定すると、UDP マルチキャスト通信用ソケットを生成します。 オプションの第四パラメータ int-ttl に TTL (time to live) 値を指定できます。 int-ttl 値が指定されない時、その値は 3 になります。
When specifying "multi" or "m" as a third parameter for str-mode, a socket for UDP multicast communications will be created. Optionally, the fourth parameter int-ttl can be specified as a TTL (time to live) value. If no int-ttl value is specified, a value of 3 is assumed.

net-connect の UDP マルチキャスト・モード指定は、ソケットを UDP マルチキャスト・モードに置くだけで、実際には目標のマルチキャスト・アドレスとの接続を確立しないことに注意してください。 受信側では、net-listen を UDP マルチキャスト・オプションで使ってください。
Note that specifying UDP multicast mode in net-connect does not actually establish a connection to the target multicast address but only puts the socket into UDP multicasting mode. On the receiving side, use net-listen together with the UDP multicast option.

;; example client I
(net-connect "" 4096 "multi")   3
(net-send-to "226.0.0.1" 4096 "hello" 3)

;; example client II
(net-connect "226.0.0.1" 4096 "multi")   3
(net-send 3 4096 "hello")

;; example server
(net-listen 4096 "226.0.0.1" "multi")   5
(net-receive-from 5 20)               
 ("hello" "192.168.1.94" 32769)

サーバー側では、ノン・ブロッキング通信に net-peeknet-select が使えます。 上の例では、データグラムが受信されるまでサーバーはブロックしています。
On the server side, net-peek or net-select can be used for non-blocking communications. In the above example, the server would block until a datagram is received.

アドレス 226.0.0.1 は、224.0.0.0 から 239.255.255.255 までのクラス D 範囲マルチキャスト・アドレス内の一マルチキャスト・アドレスです。
The address 226.0.0.1 is just one multicast address in the Class D range of multicast addresses from 224.0.0.0 to 239.255.255.255.

net-send-tonet-receive-from の代わりに、関数 net-sendnet-receive が使えます。
The net-send and net-receive functions can also be used instead of net-send-to and net-receive-from.

UDP broadcast communications(UDP ブロードキャスト通信)

第三パラメータ str-mode に文字列 "broadcast""b" を指定すると、UDP ブロードキャスト通信が設定されます。 この場合、ブロードキャスト・アドレスの最後には 255 が使われます。
Specifying the string "broadcast" or "b" in the third parameter, str-mode, causes UDP broadcast communications to be set up. In this case, the broadcast address ending in 255 is used.

;; example client
(net-connect "192.168.2.255" 3000 "broadcast")   3
(net-send 3 "hello")

;; example server
(net-listen 3000 "" "udp")   5

(net-receive 5 buff 10)
buff   "hello"
;; or
(net-receive-from 5 10)
 ("hello" "192.168.2.1" 46620)

受信側では、net-listen"" (空文字列) で指定されるデフォルト・アドレスで使われるべきだということに注意してください。 ブロードキャストは、特定のアドレスでは受信できません。 全ての UDP 通信において、net-listen は実際に受信側を待ち受け(listen)モードに置きません。 どちらかというと、ソケットを特殊 UDP モードに設定します。
Note that on the receiving side, net-listen should be used with the default address specified with an "" (empty string). Broadcasts will not be received when specifying an address. As with all UDP communications, net-listen does not actually put the receiving side in listen mode, but rather sets up the sockets for the specific UDP mode.

ノン・ブロッキング状態で通信が来たかどうかをチェックするために、関数net-selectnet-peek が使えます。
The net-select or net-peek functions can be used to check for incoming communications in a non-blocking fashion.

Local domain Unix sockets(ローカル ドメイン Unix ソケット)

第三構文の net-connect は、str-file-path を使って名付けられた ローカル ドメイン Unix ソケット を通して、ローカル・ファイル・システム上のサーバーに接続します。 成功裏に接続を持った後にソケット・ハンドルを返し、それ以外では nil を返します。
In the third syntax, net-connect connects to a server on the local file system via a local domain Unix socket named using str-file-path. Returns a socket handle after having connected successfully; otherwise, returns nil.

(net-connect "/tmp/mysocket")   3

; on OS/2 use "\\socket\\" prefix

(net-connect "\\socket\\mysocket")

ローカル・ドメイン のファイル・システム・ソケットが生成され、返されます。 サーバー側では、ローカル・ドメイン のソケット が net-listennet-accept を使って生成されています。 接続が確立された後は、通常 TCP/IP ストリーム通信に関数 net-selectnet-sendnet-receive を使います。 この形の接続は、同じファイル・システム上のプロセス間高速双方向通信チャンネルとして使われます。 この形の接続は、MS Windows プラットフォーム では利用できません。
A local domain file system socket is created and returned. On the server side, local domain sockets have been created using net-listen and net-accept. After the connection has been established the functions net-select, net-send and net-receive can be used as usual for TCP/IP stream communications. This type of connection can be used as a fast bi-directional communications channel between processes on the same file system. This type of connection is not available on MS Windows platforms.



net-error

syntax: (net-error)
syntax: (net-error int-error)

関数 net-acceptnet-connectnet-evalnet-listennet-lookupnet-receivenet-receive-udpnet-selectnet-sendnet-send-udpnet-service のいずれかを呼び出した時に発生した最後のエラーを取り出します。 これらの関数が失敗した時はいつも nil を返すので、より多くの情報を取り出すために net-error が使われます。
Retrieves the last error that occurred when calling a any of the following functions: net-accept, net-connect, net-eval, net-listen, net-lookup, net-receive, net-receive-udp, net-select, net-send, net-send-udp, and net-service. Whenever one of these functions fails, it returns nil and net-error can be used to retrieve more information.

ソケット使用通信を行う関数はソケットを自動的に閉じて、 net-sessions のリストからソケットを削除します。
Functions that communicate using sockets close the socket automatically and remove it from the net-sessions list.

net-* が成功裏に終了した場合は、エラー番号を消去します。
Each successful termination of a net-* function clears the error number.

(訳注:エラーが有る場合は)次のメッセージが返ります:
The following messages are returned:

nodescription
1Cannot open socket
2DNS resolution failed
3Not a valid service
4Connection failed
5Accept failed
6Connection closed
7Connection broken
8Socket send() failed
9Socket recv() failed
10Cannot bind socket
11Too many sockets in net-select
12Listen failed
13Badly formed IP
14Select failed
15Peek failed
16Not a valid socket
17Cannot unblock socket
18Operation timed out
19HTTP bad formed URL
20HTTP file operation failed
21HTTP transfer failed
22HTTP invalid response from server
23HTTP no response from server
24HTTP no content
25HTTP error in header
26HTTP error in chunked format



(net-error)  nil

(net-connect "jhghjgkjhg" 80)    nil

(net-error)    (2 "ERR: "DNS resolution failed") 

int-error が指定された時は、その番号とエラー番号のエラー・テキストを返します。
When int-error is specified the number and error text for that error number is returned.

(net-error 10)  (10 "Cannot bind socket")

last-errorsys-error も見てください。
See also last-error and sys-error.



net-eval

syntax: (net-eval str-host int-port exp [int-timeout [func-handler]])
syntax: (net-eval '((str-host int-port exp) ... ) [int-timeout [func-handler]])

一つ以上の newLISP サーバー上において、リモートでソースを評価するために使われます。 この関数は、リモート・サーバーへの接続に必要な全ての通信を処理し、評価用のソースを送信し、応答レスポンスを待って収集します。
Can be used to evaluate source remotely on one or more newLISP servers. This function handles all communications necessary to connect to the remote servers, send source for evaluation, and wait and collect responses.

exp 式は、目標ノードの環境下でリモートに評価されます。 exp はクォート式か文字列区切りに内包される式のどちらかです。 より大きな式には、ダブル・クォート " ... " の代わりに、 [text] ... [/text] 区切りを使うことができます。 一個より多い式を指定した時、目標ノードで全て評価されますが、最初の結果のみが返ります。
The expression in exp will be evaluated remotely in the environment of the target node. The exp is either a quoted expression, or it is enclosed in string delimiters. For bigger expressions [text] ... [/text] delimiters can be used instead of double quotes " ... ". Only one expression should be enclosed in the string. When more than one are specified, all will get evaluated in the target node, but only the result of the first will be returned.

リモート TCP/IP サーバーは、次のような方法で開始されます:
The remote TCP/IP servers are started in the following way:

newlisp -c -d 4711 &

; preloading function definitions

newlisp preload.lsp -c -d 12345 &

; logging connections

newlisp -l -c -d 4711 &

; communicating via Unix local domain sockets

newlisp -c /tmp/mysocket

newLISP がプロンプトを出すのを抑制するには、-c オプションが必要です。
The -c option is necessary to suppress newLISP emitting prompts.

デーモン・モード -d は、newLISP の接続間の状態保持を許可します。 接続間の状態保持を望まない時は、inetd デーモン モード の方が有利です。 インターネットの inetd あるいは xinetd サービス・デーモンは、各クライアント接続毎に一つの新規 newLISP プロセスを開始します。 これは、複数の接続において、より高速なサービスを作り出します。 -d デーモン・モードでは、各クライアントの要求リクエストは先行している要求リクエストが終わるのを待たなければなりません。 このモードの正しい設定方法は、inetd デーモン モード の章で見てください。
The -d daemon mode allows newLISP to maintain state between connections. When keeping state between connections is not desired, the inetd daemon mode offers more advantages. The Internet inetd or xinetd services daemon will start a new newLISP process for each client connection. This makes for much faster servicing of multiple connections. In -d daemon mode, each new client request would have to wait for the previous request to be finished. See the chapter inetd daemon mode on how to configure this mode correctly.

4711 の代わりに、他のポート番号も使えます。 異なるホストにおいて、同じか違うポート番号で、複数のノードを始められます。 通信やリモート・コマンドのログを取るために、ロギング・オプションの -l あるいは -L を指定できます。
Instead of 4711, any other port number can be used. Multiple nodes can be started on different hosts and with the same or different port numbers. The -l or -L logging options can be specified to log connections and remote commands.

第一構文の net-eval は、一つのリモート newLISP サーバー・ノードとだけ 会話トークし、str-host ホストの int-port ポートに式 exp を評価する要求リクエストを送ります。 int-timeout がない時、net-eval は接続後に 応答レスポンスがあるまで 60 秒待ちます。 一方で(訳注:int-timeout がある時)、そのミリ秒のタイム・アウト時間が経過すると nil を返します。 そうでなければ、exp の評価結果が返ります。
In the first syntax, net-eval talks to only one remote newLISP server node, sending the host in str-host on port int-port a request to evaluate the expression exp. If int-timeout is not given, net-eval will wait up to 60 seconds for a response after a connection is made. Otherwise, if the timeout in milliseconds has expired, nil is returned; else, the evaluation result of exp is returned.

; the code to be evaluated is given in a quoted expression
(net-eval "192.168.1.94" 4711 '(+ 3 4))        7

; expression as a string (only one expression should be in the string)
(net-eval "192.168.1.94" 4711 "(+ 3 4)")       7

; with timeout
(net-eval "192.168.1.94" 4711 '(+ 3 4) 1)      nil  ; 1ms timeout too short
(net-error)                                    (17 "ERR: Operation timed out")

(net-eval "192.168.1.94" 4711 '(+ 3 4) 1000)   7

; program contained in a variable
(set 'prog '(+ 3 4))
(net-eval "192.168.1.94" 4711 prog)            7

; specify a local-domain Unix socket (not available on MS Windows)
(net-eval "/tmp/mysocket" 0 '(+ 3 4))          7

net-eval の第二構文は、応答レスポンスの全てが集められるかタイム・アウトが起こると、結果のリストを返します。 タイム・アウト時の応答レスポンスには、nil が返ります。 例の最後の行は、ソケット・パスとポート番号 0 を指定してローカル・ドメイン Unix ソケットを指定する方法を示しています。 接続エラーもしくはノードに情報を送信した時に起こるエラーが、エラー番号と詳細エラー文字列のリストとして返っています。 返される可能性のあるエラー・メッセージのリストは、関数 net-error で見てください。
The second syntax of net-eval returns a list of the results after all of the responses are collected or timeout occurs. Responses that time out return nil. The last example line shows how to specify a local-domain Unix socket specifying the socket path and a port number of 0. Connection errors or errors that occur when sending information to nodes are returned as a list of error numbers and descriptive error strings. See the function net-error for a list of potential error messages.

; two different remote nodes different IPs
(net-eval '(
    ("192.168.1.94" 4711 '(+ 3 4)) 
    ("192.168.1.95" 4711 '(+ 5 6))
    ) 5000)
 (7 11)

; two persistent nodes on the same CPU different ports
(net-eval '(
    ("localhost" 8081 '(foo "abc")) 
    ("localhost" 8082 '(myfunc 123)') 
    ) 3000)

; inetd or xinetd nodes on the same server and port
; nodes are loaded on demand
(net-eval '(
    ("localhost" 2000 '(foo "abc")) 
    ("localhost" 2000 '(myfunc 123))
    ) 3000)

最初の例は、二つの異なるリモート・ノードで評価される二つの式を示しています。 二番目の例は、ローカル・コンピュータ上の二つのノードに対してです。 コンピュータ上のマルチCPUのデバックや優位性を語る上で、これが役立つかもしれません。 ポート番号に 0 を指定すると、net-eval はホスト名としてローカル・ドメイン Unix ソケットへのフルパスを取ります。
The first example shows two expressions evaluated on two different remote nodes. In the second example, both nodes run on the local computer. This may be useful when debugging or taking advantage of multiple CPUs on the same computer. When specifying 0 for the port number , net-eval takes the host name as the file path to the local-domain Unix socket.

foomyfunc の定義が両方共、目標環境に存在しなければならないことに注意してください。 これは、前もって define 宣言文を送信して net-eval を使えば可能です。 リモート・ノードの開始時に、コードをロードして置くことでも可能です。
Note that definitions of foo and myfunc must both exist in the target environment. This can be done using a net-eval sending define statements before. It also can be done by preloading code when starting remote nodes.

ノードが、inetd か xinetd の制御下であれば、いくつかのノードが同じ IP アドレスとポートを持てるかもしれません。 この場合、Unix のデーモン inetd または xinetd が 要求リクエストに応じて複数の newLISP を開始します。 これは、たった一つしかないマシンで配布プログラムをテストする時に役立ちます。 最後の例が、その状況を示しています。 プラットフォーム OS が異なる CPU コアに異なるプロセスを配置できるマルチ・コア CPU 上でも役立ちます。
When nodes are inetd or xinetd-controlled, several nodes may have the same IP address and port number. In this case, the Unix daemon inetd or xinetd will start multiple newLISP servers on demand. This is useful when testing distributed programs on just one machine. The last example illustrates this case. It is also useful on multi core CPUs, where the platform OS can distribute different processes on to different CPU cores.

評価のために送るソースには、複数ラインのプログラムを含めることができます。 この方法では、リモート・ノードは最初にプログラムをロードし、その後に特定の関数を呼び出せます。 大規模プログラム・ファイルのプログラム転送には、関数 put-urlsave(URL ファイル名を使用)を使えます。 net-eval 宣言文がこれらのプログラムをロードできます。
The source sent for evaluation can consist of entire multiline programs. This way, remote nodes can be loaded with programs first, then specific functions can be called. For large program files, the functions put-url or save (with a URL file name) can be used to transfer programs. The a net-eval statement could load these programs.

オプションでハンドラ関数を指定できます。 この関数は、待ち時間毎に繰り返し呼び出され、リモート評価が全て終了した時にも一回呼び出されます。
Optionally, a handler function can be specified. This function will be repeatedly called while waiting and once for every remote evaluation completion.

(define (myhandler param)
    (if param
        (println param))
)

(set 'Nodes '(
    ("192.168.1.94" 4711)
    ("192.168.1.95" 4711)
))

(set 'Progs '(
    (+ 3 4)
    (+ 5 6)
))

(net-eval (map (fn (n p) (list (n 0) (n 1) p)) Nodes Progs) 5000 myhandler)

("192.168.1.94" 4711 7)
("192.168.1.95" 4711 11)

例では、ノード指定のリストがノードのリストと評価用ソースから組み立てられる様子を示しています。 これは、多数のリモート・ノードとの接続時に役立つかもしれません。
The example shows how the list of node specs can be assembled from a list of nodes and sources to evaluate. This may be useful when connecting to a larger number of remote nodes.

(net-eval (list 
  (list (Nodes 0 0) (Nodes 0 1) (Progs 0)) 
  (list (Nodes 1 0) (Nodes 1 1) (Progs 1)) 
 ) 3000 myhandler)

リモート・ノードからの入力を待っている間、myhandler は引数 paramnil にして呼び出されます。 リモート・ノードの結果が全て受信されると、リモート・ホスト名か IP 番号 かポートと結果の式からなるリストにセットされた parammyhandler が呼び出されます。 net-eval は、タイム・アウト前に true を返し、タイム・アウトに達するか過ぎた時に nil を返します。 タイム・アウトを過ぎた全てのリモート・ホストは、結果のリストに nil を含みます。
While waiting for input from remote hosts, myhandler will be called with nil as the argument to param. When a remote node result is completely received, myhandler will be called with param set to a list containing the remote host name or IP number, the port, and the resulting expression. net-eval will return true before a timeout or nil if the timeout was reached or exceeded. All remote hosts that exceeded the timeout limit will contain a nil in their results list.

より長い例には、このプログラムを見てください:mapreduce。 この例は、単語計数タスクを三つのリモート・ノードに配布する方法を示しています。 三つのノードは異なるテキストの単語を計数し、マスター・ノードが結果を受け取り、まとめます。
For a longer example see this program: mapreduce. The example shows how a word counting task gets distributed to three remote nodes. The three nodes count words in different texts and the master node receives and consolidates the results.



net-interface

syntax: (net-interface str-ip-addr)
syntax: (net-interface)

ネットワーク通信に使われるデフォルトのローカル・インターフェイス・アドレスを設定します。 設定していなければ、net-listen に与えられるインターフェイス・アドレスで上書きされていない限り、ネットワーク関数は内部デフォルト・アドレスをデフォルトにします。
Sets the default local interface address to be used for network connections. If not set then network functions will default to an internal default address, except when overwritten by an optional interface address given in net-listen.

str-ip-addr を指定しない時には、現行のデフォルト値が返ります。 その以前に、net-interface を IP アドレス指定に使っていなければ、アドレス 0.0.0.0 が返ります。 これは、ネットワーク・ルーチン全てがオペレーティング・システム下で予め設定されたデフォルト・アドレスを使うことを意味します。
When no str-ip-addr is specified, the current default is returned. If the net-interface has not been used yet to specify an IP address, the address 0.0.0.0 is returned. This means that all network routines will use the default address preconfigured by the underlying operating system.

複数のネットワーク・インターフェイス・ハードウェアを持つか、複数のIP番号を用意しているマルチ・ホーム・サーバでのみ、この関数を使います。 ネットワーク関数は他の機器において、インストールされている単一ネットワークを自動的に選択するからです。
This function has only usage on multihomed servers with either multiple network interface hardware or otherwise supplied multiple IP numbers. On all other machines network functions will automatically select the single network interface installed.

関数はエラー発生時に nil を返し、エラー内容を報告させるために net-error を使えます。
On error the function returns nil and net-error can be used to report the error.

(net-interface "192.168.1.95")   "192.168.1.95"
(net-interface "localhost")      "127.0.0.1"

インターフェイス・アドレスには、IP アドレスか名前を指定できます。 戻り値は str-ip-addr に与えられたアドレスです。
An interface address can be defined as either an IP address or a name. The return value is the address given in str-ip-addr



net-ipv

syntax: (net-ipv int-version)
syntax: (net-ipv)

インターネット・プロトコル・バージョンの IPv4 と IPv6 間を切り替えます。 int-version は、IPv4 の 4 か IPv6 の 6 が入ります。 パラメータが無い時、net-ipv は現在の設定を返します。
Switches between IPv4 and IPv6 internet protocol versions. int-version contains either a 4 for IPv4 or a 6 for IPv6. When no parameter is given, net-ipv returns the current setting.

(net-ipv)       4
(net-ipv 6)     6

デフォルトの newLISP は IPv4 モードで開始します。 newLISP スタート時は、コマンド・ラインから IPv6 プロトコル・モードを指定できます:
By default newLISP starts up in IPv4 mode. The IPv6 protocol mode can also be specified from the commandline when starting newlisp:

newlisp -6

ソケットを net-connect で接続するか、net-listen で待ち受け(listen)するなら、関数net-acceptnet-selectnet-sendnet-receivenet-receive-from は、ソケットを生成した時に使わるアドレス・プロトコルに自動的に合わせます。 IPv4/6 設定の異なる接続を同時に開くことができます。
Once a socket is connected with either net-connect or listened on with net-listen, the net-accept, net-select, net-send, net-receive and net-receive-from functions automatically adjust to the address protocol used when creating the sockets. Different connections with different IPv4/6 settings can be open at the same time.

現行の net-packet は IPv6 をサポートせず、設定にかかわらず IPv4 で動作することに注意してください。
Note, that currently net-packet does not support IPv6 and will work in IPv4 mode regardless of settings.



net-listen

syntax: (net-listen int-port [str-ip-addr [str-mode]])
syntax: (net-listen str-file-path)

int-port で指定されたポートを待ち受け(listen)ます。 net-listen の呼び出しは直ちにソケット番号を返し、その番号は後で接続を待つブロッキング関数 net-accept で使われることになります。 net-accept は接続が受け入れられるとすぐに、接続しているクライアントとの通信に使われるソケット番号を返します。
Listens on a port specified in int-port. A call to net-listen returns immediately with a socket number, which is then used by the blocking net-accept function to wait for a connection. As soon as a connection is accepted, net-accept returns a socket number that can be used to communicate with the connecting client.

(set 'port 1234)
(set 'listen (net-listen port))
(unless listen (begin
    (print "listening failed\n")
    (exit)))

(print "Waiting for connection on: " port "\n")

(set 'connection (net-accept listen))
(if connection
    (while (net-receive connection buff 1024 "\n")
        (print buff)
        (if (= buff "\r\n") (exit)))
    (print "Could not connect\n"))

例では、ポート 1234 の接続を待って、それから、空のラインを受け取るまで入力ラインを読み込みます。 Unix システムで 1024 より小さいポートを待ち受け(listen)ることは、スーパー・ユーザ・アクセスを要求する事に注意してください。
The example waits for a connection on port 1234, then reads incoming lines until an empty line is received. Note that listening on ports lower than 1024 may require superuser access on Unix systems.

一個より多いインターフェイス・カードを持つコンピュータ上では、str-ip-addr オプションにインターフェイス IP アドレスか名前を指定して、net-listen に指定したアドレスの待ち受け(listen)を指示します。
On computers with more than one interface card, specifying an optional interface IP address or name in str-ip-addr directs net-listen to listen on the specified address.

;; listen on a specific address
(net-listen port "192.168.1.54") 

Local domain Unix sockets(ローカル ドメイン Unix ソケット)

第二構文の net-listen は、str-file-path を使って名前付けられたローカル・ドメイン Unix ソケット を通して、ローカル・ファイル・システム上のクライアントを待ち受け(listen)ます。 成功すればソケット・ハンドルを返し、それを使って net-accept がクライアントとの接続を受け入れることができます。成功しなければ nil を返します。
In the second syntax, net-listen listens for a client on the local file system via a local domain Unix socket named using str-file-path. If successful, returns a socket handle that can be used with net-accept to accept a client connection; otherwise, returns nil.

(net-listen "/tmp/mysocket")   5

; on OS/2 use "\\socket\\" prefix

(net-listen "\\socket\\mysocket")

(net-accept 5)

ローカル・ドメイン・ファイル・システム・ソケットが生成され、待ち受け(listen)状態になっています。 クライアントは、同じ str-file-path を使って接続を試みます。 接続が関数 net-select に受け入れられた後、通常の TCP/IP ストリーム通信に net-sendnet-receive を使うことができます。 この形の接続は、同じファイル・システム上のプロセス間高速双方向通信チャンネルとして使えます。 この形の接続は、MS Windows プラットフォームでは使えません。
A local domain file system socket is created and listened on. A client will try to connect using the same str-file-path. After a connection has been accepted the functions net-select, net-send and net-receive can be used as usual for TCP/IP stream communications. This type of connection can be used as a fast bi-directional communications channel between processes on the same file system. This type of connection is not available on MS Windows platforms.

UDP communications(UDP 通信)

第三パラメータとして、str-mode にオプション文字列 "udp" または "u" を指定でき、UDP(ユーザ・データグラム・プロトコル)通信に適したソケット一式を生成します。 TCP 通信にのみ使われる net-accept を使うこと無し に、この方法で作られたソケットを net-receive-from に直接使うことができ、入力 UDPデータを待ちます。 net-receive-from 呼び出しは、UDP データ・パケットを受信するまでブロックします。 代わりの方法として、ノン・ブロッキング状態でデータが準備できたかどうかのチェックするために、net-selectnet-peek を使うことができます。 net-receive-from で受け取ったアドレスとポートへのデータ返送には、net-send-to を使ってください。
As a third parameter, the optional string "udp" or "u" can be specified in str-mode to create a socket suited for UDP (User Datagram Protocol) communications. A socket created in this way can be used directly with net-receive-from to await incoming UDP data without using net-accept, which is only used in TCP communications. The net-receive-from call will block until a UDP data packet is received. Alternatively, net-select or net-peek can be used to check for ready data in a non-blocking fashion. To send data back to the address and port received with net-receive-from, use net-send-to.

UDP 通信は、アドレス情報としての接続ソケットを保持しないので、net-peer が動作しないことに注意してください。
Note that net-peer will not work, as UDP communications do not maintain a connected socket with address information.

(net-listen 10002 "192.168.1.120" "udp") 

(net-listen 10002 "" "udp") 

一番目の例は、指定したネットワーク・アダプタを待ち受け(listen)ます。 一方で、二番目の例はデフォルト・アダプタを待ち受け(listen)ます。 どちらの呼び出しもソケット番号を返し、引き続く関数 net-receivenet-receive-fromnet-send-tonet-selectnet-peek の呼び出しに使われます。
The first example listens on a specific network adapter, while the second example listens on the default adapter. Both calls return a socket number that can be used in subsequent net-receive, net-receive-from, net-send-to, net-select, or net-peek function calls.

UDP サーバー UDP クライアントのどちらも、net-listen"udp" オプションを使って設定されます。 このモードでは、net-listen が実際に TCP/IP 通信を待ち受け(listen) ることはありません。 ローカル・インターフェイスのアドレスとポートにソケットを束縛するだけです。
Both a UDP server and UDP client can be set up using net-listen with the "udp" option. In this mode, net-listen does not really listen as in TCP/IP communications; it just binds the socket to the local interface address and port.

動作例としては、newLISP 配布ソースにあるファイル examples/clientexamples/server を見てください。
For a working example, see the files examples/client and examples/server in the newLISP source distribution.

一つのデータ・パケットだけような短い処理には、"udp" オプションの net-listen の代わりに、関数 net-receive-udpnet-send-udp を使うことができます。
Instead of net-listen and the "udp" option, the functions net-receive-udp and net-send-udp can be used for short transactions consisting only of one data packet.

net-listennet-selectnet-peek は、ノン・ブロッキング読み出しを簡単にするために使われます。 待ち受け(listen)/読み出しソケットが閉じらないだけでなく、引き続き読み出しに使えるからです。 対照的に、net-receive-udpnet-send-udp のペアの使用は、どちらのサイドも送受信終了後、ソケットを閉じます。
net-listen, net-select, and net-peek can be used to facilitate non-blocking reading. The listening/reading socket is not closed but is used again for subsequent reads. In contrast, when the net-receive-udp and net-send-udp pair is used, both sides close the sockets after sending and receiving.

UDP multicast communications(UDP マルチキャスト通信)

オプション文字列 str-mode"multi""m" を指定すると、net-listen はマルチキャストに適切なソケットを返します。 この場合、str-ip-addr にはマルチキャスト・アドレス範囲 224.0.0.0239.255.255.255 中の一つが入ります。 net-listenstr-ip-addr をマルチキャスト伝送受信用アドレスとして登録します。 このアドレスをサーバー・ホストの IP アドレス と混同してはいけません。
If the optional string str-mode is specified as "multi" or "m", net-listen returns a socket suitable for multicasting. In this case, str-ip-addr contains one of the multicast addresses in the range 224.0.0.0 to 239.255.255.255. net-listen will register str-ip-addr as an address on which to receive multicast transmissions. This address should not be confused with the IP address of the server host.

;; example client

(net-connect "226.0.0.1" 4096 "multi")   3

(net-send-to "226.0.0.1" 4096 "hello" 3)


;; example server

(net-listen 4096 "226.0.0.1" "multi")   5

(net-receive-from 5 20)               
 ("hello" "192.168.1.94" 32769)

サーバー側では、ノン・ブロッキング通信に net-peeknet-select が使われます。 上記例のサーバーは、データが受信されるまでブロックします。
On the server side, net-peek or net-select can be used for non-blocking communications. In the example above, the server would block until a datagram is received.

関数 net-send-tonet-receive-from の代わりに、net-sendnet-receive が使えます。
The net-send and net-receive functions can be used instead of net-send-to and net-receive-from.

Packet divert sockets and ports(パケット迂回ソケットとポート)

BSD ライクのプラットフォーム上で、str-mode"divert" が指定されると、int-port を迂回ポートとする迂回ソケットが生成されます。 IP アドレスの内容 str-ip-addr は無視されます。 int-port だけが有効で、返される生のソケットに束縛されます。
If str-mode is specified as "divert", a divert socket can be created for a divert port in int-port on BSD like platforms. The content of IP address in str-ip-addr is ignored and can be specified as an empty string. Only the int-port is relevant and will be bound to the raw socket returned.

net-listen で迂回オプションを使うには、newLISP が特権モードで走っていなければなりません。 このオプションは、 Unix ライクのプラットフォームでのみ利用可能です。
To use the divert option in net-listen, newLISP must run in super-user mode. This option is only available on Unix like platforms.

divert ソケットは、迂回ポートに迂回された生ソケットを全て受け取ります。 また、パケットは迂回ソケットに書き戻されるかもしれず、その場合のパケットは OS カーネルの IP パケット処理に再び入ります。
The divert socket will receive all raw packets diverted to the divert port. Packets may also be written back to a divert socket, in which case they re-enter OS kernel IP packet processing.

迂回ポートへのパケット迂回ルールは、BSD の ipfw か Linux の ipchains かどちらかの設定ユーティリティで定義されていなければなりません。
Rules for packet diversion to the divert port must be defined using either the ipfw BSD or ipchains Linux configuration utilities.

net-listen 宣言文で生成され、返された迂回ソケット上の生パケットの読み書きには、関数 net-receive-fromnet-send-to が使われます。 パケット再入の際、net-receive-from で受け取ったのと同じアドレスが net-send-to 呼び出しに使われます:
The net-receive-from and net-send-to functions are used to read and write raw packets on the divert socket created and returned by the net-listen statement. The same address received by net-receive-from is used in the net-send-to call when re-injecting the packet:

; rules have been previously configured for a divert port
(set 'divertSocket (net-listen divertPort "" "divert"))

(until (net-error)
    (set 'rlist (net-receive-from divertSocket maxBytes))
    (set 'buffer (rlist 1))
    ; buffer can be processed here before reinjecting
    (net-send-to (rlist 0) divertPort buffer divertSocket)
)

詳細な情報は、Unix man ページで divert の項か、設定ユーティリティ ipfw (BSDs) か ipchains (Linux) を見てください。
For more information see the Unix man pages for divert and the ipfw (BSDs) or ipchains (Linux) configuration utilities.



net-local

syntax: (net-local int-socket)

ローカル・コンピュータの int-socket で指定された接続用 IP 番号とポートを返します。
Returns the IP number and port of the local computer for a connection on a specific int-socket.

(net-local 16)   ("204.179.131.73" 1689)

リモート・コンピュータの IP 番号とボートへのアクセスには、関数 net-peer を使ってください。
Use the net-peer function to access the remote computer's IP number and port.



net-lookup

syntax: (net-lookup str-ip-number)
syntax: (net-lookup str-hostname [bool])

IP ドット形式の str-ip-number からホスト名の文字列を返すか、str-hostname からドット形式の IP 番号を返します。
Returns either a hostname string from str-ip-number in IP dot format or the IP number in dot format from str-hostname:

(net-lookup "209.24.120.224")     "www.nuevatec.com"
(net-lookup "www.nuevatec.com")   "209.24.120.224"

(net-lookup "216.16.84.66.sbl-xbl.spamhaus.org" true)
 "216.16.84.66"

第二構文では、オプションの bool フラグを指定できます。 bool の式が nil 以外に評価されると、(訳注:引数の)名前文字列が IP 番号で始まっていたとしても、ホスト名からの検索になります。
Optionally, a bool flag can be specified in the second syntax. If the expression in bool evaluates to anything other than nil, host-by-name lookup will be forced, even if the name string starts with an IP number.



net-packet

syntax: (net-packet str-packet)

この関数は、raw sockets インターフェイスを通して送信されるカスタム構成のネットワーク・パケットを許可します。 str-packet のパケットは、TCP か UDP か ICMP ヘッダーのいずれかとオプション・データが続く IP(インターネット・プロトコル)ヘッダーで始まっていなければなりません。 newLISP はスーパー・ユーザ特権で走っている必要があります。 また、この関数は macOS、Linux、その他の Unix オペレーティングシステムにおいて、IPv4 でのみ利用可能です。 現在の net-packet は IPv4 用のみであり、macOS、Linux、OpenBSD で試してあります。
The function allows custom configured network packets to be sent via a raw sockets interface. The packet in str-packet must start with an IP (Internet Protocol) header followed by either a TCP, UDP or ICMP header and optional data. newLISP must be run with super user privileges, and this function is only available on macOS, Linux and other Unix operating systems and only for IPv4. Currently net-packet is IPv4 only and has been tested on macOS, Linux and OpenBSD.

この関数は、成功時に送信バイト数を返します。 失敗時には nil を返しますので、net-errorsys-error の両方で調べたほうがよいでしょう。
On success the function returns the number of bytes sent. On failure the function returns nil and both, net-error and sys-error, should be inspected.

カスタム構成のパケットのチェックサム・フィールドにゼロが入っている時は、 net-packet が正しいチェックサムを計算して挿入します。 すでにチェックサムがある時は触らず、そのままにます。
When custom configured packets contain zeros in the checksum fields, net-packet will calculate and insert the correct checksums. Already existing checksums stay untouched.

次の例は、IP 番号 192.168.1.92 に UDP パケットを送り込みます。 IP ヘッダーは、目標 IP 番号で終わる 20 バイトからなります。 続く UDP ヘッダーは 8 バイトの長さを持ち、データ文字列 Hello World が続きます。 両ヘッダーのチェックサム・バイトである 0x00 0x00 は破棄され、内部で再計算されます。
The following example injects a UDP packet for IP number 192.168.1.92. The IP header consists of 20 bytes ending with the target IP number. The following UDP header has a length of 8 bytes and is followed by the data string Hello World. The checksum bytes in both headers are left as 0x00 0x00 and will be recalculated internally.

; packet as generated by: (net-send-udp "192.168.1.92" 12345 "Hello World")

(set 'udp-packet (pack (dup "b" 39) '(
    0x45 0x00 0x00 0x27 0x4b 0x8f 0x00 0x00 0x40 0x11 0x00 0x00 192  168  1    95
    192  168  1    92   0xf2 0xc8 0x30 0x39 0x00 0x13 0x00 0x00 0x48 0x65 0x6c 0x6c
    0x6f 0x20 0x57 0x6f 0x72 0x6c 0x64)))

(unless (net-packet udp-packet)
    (println "net-error: " (net-error))
    (println "sys-error: " (sys-error)))

関数 net-packet は、ネット・セキュリティのテスト時に使われます。 その際の不正なアプリケーションは、ネットワーク・ルーターやネットワークに繋がった他のデバイスの正しい機能を阻害しかねません。 そのため、この関数はうまく隔離されたプライベート・イントラ・ネット上で使用すべきであり、使用者もネットワークの専門家に限定すべきです。
The net-packet function is used when testing net security. Its wrong application can upset the correct functioning of network routers and other devices connected to a network. For this reason the function should only be used on well isolated, private intra-nets and only by network professionals.

他のパケット構成の例は、newLISP 配布ソースにあるファイル qa-specific-tests/qa-packet を見てください。
For other examples of packet configuration, see the file qa-specific-tests/qa-packet in the newLISP source distribution.



net-peek

syntax: (net-peek int-socket)

int-socket のネットワーク・ソケット上で読み取り可能なバイト数を返します。 エラーが起こっているか、接続が閉じている時は nil を返します。
Returns the number of bytes ready for reading on the network socket int-socket. If an error occurs or the connection is closed, nil is returned.

(set 'aSock (net-connect "aserver.com" 123))

(while ( = (net-peek aSock) 0) 
    (do-something-else))

(net-receive aSock buff 1024)

このプログラムは接続後、aSock が読み込み可能になるまで while ループで待ちます。
After connecting, the program waits in a while loop until aSock can be read.

ファイル記述子デスクリプタstdin のチェックには、関数 peek を使ってください。
Use the peek function to check file descriptors and stdin.



net-peer

syntax: (net-peer int-socket)

int-socket で接続しているリモート・コンピュータの IP 番号とポートを返します。
Returns the IP number and port number of the remote computer for a connection on int-socket.

(net-peer 16)   ("192.100.81.100" 13)

ローカル・コンピュータの IP アドレスとポート番号のアクセスには、関数 net-local を使ってください。
Use the net-local function to access the local computer's IP number and port number.



net-ping

syntax: (net-ping str-address [int-timeout [int-count bool]]])
syntax: (net-ping list-addresses [int-timeout [int-count bool]]])

この関数は Unix ベースのシステム上でのみ利用可能で、(訳注:newLISPが)スーパー・ユーザ・モードで走っていなければなりません。 例えば、macOS か 他の BSD での newLISP 開始時に sudo newlisp を使うとか、Linux の root ユーザで使うとかです。 IPv6 アドレス・モードでは、ブロードキャスト・モードや -(ハイフン)または *(アスタリスク)を使った範囲指定が使えません。
This function is only available on Unix-based systems and must be run in superuser mode, i.e. using: sudo newlisp to start newLISP on macOS or other BSD's, or as the root user on Linux. Broadcast mode and specifying ranges with the - (hyphen) or * (star) are not available on IPv6 address mode.

macOS では、スーパー・ユーザ・モードが要求されません。
Superuser mode is not required on macOS.

第一構文の net-ping は、ICMP 64バイトのエコー要求リクエストstr-address で指定されたアドレスに送ります。 アドレスがブロードキャスト・アドレスなら、ICMP パケットは全てのサブネットで受信されます。 セキュリティ上の理由から、多くのコンピュータは ICMP ブロードキャスト ping(ICMP_ECHO)要求リクエストに返信しないので、注意してください。 オプションのタイムアウト・パラメータを int-timeout に指定できます。 タイムアウトが指定されていなければ、1000ミリ秒(1秒)になります。
In the first syntax, net-ping sends a ping ICMP 64-byte echo request to the address specified in str-address. If it is a broadcast address, the ICMP packet will be received by all addresses on the subnet. Note that for security reasons, many computers do not answer ICMP broadcast ping (ICMP_ECHO) requests. An optional timeout parameter can be specified in int-timeout. If no timeout is specified, a waiting time of 1000 milliseconds (one second) is assumed.

net-ping は、 IP 文字列と応答レスポンスが返るまでのミリ秒単位の往復の時間のリスト群をリストしたものか、応答レスポンスが返らなかった時の空のリストのどちらかを返します。
net-ping returns either a list of lists of IP strings and round-trip time in microseconds for which a response was received or an empty list if no response was received.

nil の戻り値は失敗を意味します。 エラー・メッセージを取り出すためには、関数 net-error を使ってください。 メッセージが Cannot open socket なら、おそらく newLISP は root 権限無しで動作しています。 (訳注:その場合は、)newLISP を次のような使い方で開始します:
A return value of nil indicates a failure. Use the net-error function to retrieve the error message. If the message reads Cannot open socket, it is probably because newLISP is running without root permissions. newLISP can be started using:

sudo newlisp

あるいは、スーパーユーザ・モードで走らせる set-user-ID bit を設定して、newLISP をインストールすることもできます。
Alternatively, newLISP can be installed with the set-user-ID bit set to run in superuser mode.

(net-ping "newlisp.org")      (("66.235.209.72" 634080))
(net-ping "127.0.0.1")        (("127.0.0.1" 115))
(net-ping "yahoo.com" 3000)   nil

第二構文の net-pingバッチ・モード で走ります。 このモードでは一つのソケットのみが開かれますが、複数の ICMP パケットがリストまたは範囲で指定される複数のアドレスに各々一個ずつ送られます。 パケットはできる限り早く送信されます。 この場合、複数の応答レスポンスが受信されます。 同じアドレスを複数回指定すると、受信 IP アドレスが ICMP パケットで溢れることになります。
In the second syntax, net-ping is run in batch mode. Only one socket is opened in this mode, but multiple ICMP packets are sent out—one each to multiple addresses specified in a list or specified by range. Packets are sent out as fast as possible. In this case, multiple answers can be received. If the same address is specified multiple times, the receiving IP address will be flooded with ICMP packets.

ブロードキャストやバッチ・モードで待っている応答レスポンスの数を制限するために、受信応答レスポンスの最大数を指示する追加の引数を int-count に指定できます。 このパラメータの使えば、指定したタイムアウトより早く関数を戻せます。 与えられた応答レスポンス数を受信すると、net-ping はタイムアウト前でも戻ります。 em>int-count を指定しないか 0 を指定した時、int-count は送り出したパケット数になります。
To limit the number of responses to be waited for in broadcast or batch mode, an additional argument indicating the maximum number of responses to receive can be specified in int-count. Usage of this parameter can cause the function to return sooner than the specified timeout. When a given number of responses has been received, net-ping will return before the timeout has occurred. Not specifying int-count or specifying 0 assumes an int-count equal to the number of packets sent out.

第3オプション・パラメータとして true 値を指定できます。 この設定は、ホストが返答しない場合、応答レスポンス時間の代わりにエラー文字列を返します。
As third optional parameter, a true value can be specified. This setting will return an error string instead of the response time, if the host does not answer.

(net-ping '("newlisp.org" "192.168.1.255") 2000 20)
 (("66.235.209.72" 826420) ("192.168.1.1" 124) ("192.168.1.254" 210))

(net-ping "192.168.1.*" 500) ; from 1 to 254
 (("192.168.1.1" 120) ("192.168.1.2" 245) ("192.168.2.3" 180) ("192.168.2.254" 234))

(net-ping "192.168.1.*" 500 2) ; returns after 2 responses
 (("192.168.1.3" 115) ("192.168.1.1" 145))

(net-ping "192.168.1.1-10" 1000) ; returns after 1 second
 (("192.168.1.3" 196) ("192.168.1.1" 205))

(net-ping '("192.168.1.100-120" "192.168.1.124-132") 2000) ; returns after 2 seconds
 ()

一つの net-ping 文の中に、ブロードキャストやバッチ・モードを——通常のアドレスや IP 番号またはホスト名と同様に——リスト中に IP の種類全てを置くことで混在可能です。
Broadcast or batch mode—as well as normal addresses and IP numbers or hostnames— can be mixed in one net-ping statement by putting all of the IP specs into a list.

第二、第三行は、net-ping のバッチ・モードが IP 番号の最後のサブネット・オクテットにワイルドカード文字の *(アスタリスク)を指定して始められることを示しています。 第四、第五行は、IP 番号最後のサブネット・オクテットに IP 範囲を指定できることを示しています。 net-ping は、* の 1~254 までか指定された範囲のどちらかの番号全てで、各アドレスへの ICMP パケット送信を繰り返します。 これは、IP オクテットに 255 を指定した ブロードキャスト・モードとは異なることに注意してください。 ブロードキャスト・モードでは、net-ping は一パケットのみを送出し、それが複数のアドレスで受信されます。 バッチ・モードは明示的に複数のパケットを生成し、それらは各ターゲット・アドレス毎に一個ずつです。 ブロードキャスト・モードを指定した時も int-count を指定すべきです。
The second and third lines show how the batch mode of net-ping can be initiated by specifying the * (asterisk) as a wildcard character for the last subnet octet in the IP number. The fourth and fifth lines show how an IP range can be specified for the last subnet octet in the IP number. net-ping will iterate through all numbers from either 1 to 254 for the star * or the range specified, sending an ICMP packet to each address. Note that this is different from the broadcast mode specified with an IP octet of 255. While in broadcast mode, net-ping sends out only one packet, which is received by multiple addresses. Batch mode explicitly generates multiple packets, one for each target address. When specifying broadcast mode, int-count should be specified, too.

バッチ・モードで、一つのソケットに大規模な IP リストを送る時は、 全パケットを一つのソケットに送出する時間を十分与えるために、より長いタイムアウトが必要となります。 タイムアウトが短過ぎると、関数 net-ping は不完全なリストか空リスト () を返すかもしれません。 このような場合、 net-error はタイムアウト・エラーを返すでしょう。 エラー時は nil が返り、 net-errorをエラー・メッセージの取り出しに使えます
When sending larger lists of IPs in batch mode over one socket, a longer timeout may be necessary to allow enough time for all of the packets to be sent out over one socket. If the timeout is too short, the function net-ping may return an incomplete list or the empty list (). In this case, net-error will return a timeout error. On error, nil is returned and net-error can be used to retrieve an error message.

いくつかのシステムでは、タイムアウト指定に関わらず、決められた長さのリストしか扱えないかもしれません。 この場合、範囲をいくつかに分けて、複数のnet-ping を実施すべきです。 いずれにせよ、net-ping はできる限り早くパッケージを送出します。
On some systems only lists up to a specific length can be handled regardless of the timeout specified. In this case, the range should be broken up into sub-ranges and used with multiple net-ping invocations. In any case, net-ping will send out packages as quickly as possible.



net-receive !

syntax: (net-receive int-socket sym-buffer int-max-bytes [wait-string])

ソケット int-socket 上のデータを受信し、sym-buffer の文字列に入れます。 sym-buffer には、ユーザ定義関数に参照を渡すコンテキスト・シンボルで指定されたデフォルト・ファンクタも使えます。
Receives data on the socket int-socket into a string contained in sym-buffer. sym-buffer can also be a default functor specified by a context symbol for reference passing in and out of user-defined functions.

int-max-bytes の最大値まで受信します。 net-receive は読み取ったバイト数を返します。 接続が切断されると nil を返します。 sym-buffer で用意された領域は、読み取ったバイト数の大きさになります。
A maximum of int-max-bytes is received. net-receive returns the number of bytes read. If there is a break in the connection, nil is returned. The space reserved in sym-buffer is exactly the size of bytes read.

net-receive はブロッキング呼び出しなので、int-socket にデータが届くまで戻らないことに注意してください。 ソケットが読み出し可能かどうかを知るには、 net-peeknet-select を使ってください。
Note that net-receive is a blocking call and does not return until the data arrives at int-socket. Use net-peek or net-select to find out if a socket is ready for reading.

オプションで、第四パラメータに wait-string を指定できます。 その際、net-receivewait-string に一致した文字か文字列を受信した後で返ります。 wait-stringsym-buffer に入るデータの一部となります。
Optionally, a wait-string can be specified as a fourth parameter. net-receive then returns after a character or string of characters matching wait-string is received. The wait-string will be part of the data contained in sym-buffer.

(define (gettime)
    (set 'socket (net-connect "netcom.com" 13))
    (net-receive socket buf 256)
    (print buf "\n")
    (net-close socket))

gettime を呼び出すと、プログラムは netcom.com サーバーのポート 13 に接続します。 ポート 13 は、ほとんどのサーバーに用意されている日時サービスです。 接続すると、サーバーは日付と時刻からなる文字列を送ってきます。
When calling gettime, the program connects to port 13 of the server netcom.com. Port 13 is a date-time service on most server installations. Upon connection, the server sends a string containing the date and time of day.

(define (net-receive-line socket sBuff)
    (net-receive socket sBuff 256 "\n"))

(set 'bytesReceived (net-receive-line socket 'sm))

二番目の例では、(この例では、一文字からなる文字列の)改行文字か256文字を受信後に戻る関数 net-receive-line を新たに定義しています。 文字列 "\n" は、sBuff の中身の一部です。
The second example defines a new function net-receive-line, which returns after receiving a newline character (a string containing one character in this example) or 256 characters. The "\n" string is part of the contents of sBuff.

第四パラメータを指定した時、net-receive は情報を一文字ずつ読み取るので、通常より遅くなることに注意してください。 多くの場合、速度の違いは無視できる程度かもしれません。
Note that when the fourth parameter is specified, net-receive is slower than the normal version because information is read character-by-character. In most situations, the speed difference can be neglected.



net-receive-from

syntax: (net-receive-from int-socket int-max-size)

net-receive-from は、ノン・ブロッキング通信の設定に使われます。 int-socket のソケットは、("udp" オプションと共に)net-listennet-connect で予め開かれていなければなりません。 int-max-size は、受信する最大バイト数を指定します。 それ以上受信は、Linux/BSD 上では破棄され、MS Windows 上では net-receive-fromnil を返してソケットを閉じます。
net-receive-from can be used to set up non-blocking UDP communications. The socket in int-socket must previously have been opened by either net-listen or net-connect (both using the "udp" option). int-max-size specifies the maximum number of bytes that will be received. On Linux/BSD, if more bytes are received, those will be discarded; on MS Windows, net-receive-from returns nil and closes the socket.

net-receive は、成功時にデータ文字列、リモート IP 番号、使用されたリモート・ポートのリストを返します。 失敗時には nil を返します。
On success net-receive returns a list of the data string, remote IP number and remote port used. On failure it returns nil.

;; bind port 1001 and the default address
(net-listen 1001 "" "udp")   1980 

;; optionally poll for arriving data with 100ms timeout
(while (not (net-select 1980 "r" 100000)) (do-something ... ))

(net-receive-from 1980 20)   ("hello" "192.168.0.5" 3240)

;; send answer back to sender
(net-send-to "192.168.0.5" 3240 "hello to you" 1980)

(net-close 1980) ; close socket

この例の二行目は、任意の行です。 この行が無くても、net-receive-from 呼び出しはデータが届くまでブロックします。 UDP サーバーは、幾つかのポートを待ち受け(listen)てポーリングするように設定されており、ポートが受け取るデータを配給します。
The second line in this example is optional. Without it, the net-receive-from call would block until data arrives. A UDP server could be set up by listening and polling several ports, serving them as they receive data.

受信側と送信側の両方とも、UDP モードの net-listen をっ発行しなけれななりません。 TCP/IP プロトコル通信で待ち受け(listen)るためではなく、ポートやアドレスに束縛されたソケットを生成するためです。 例題の完全版は、配布ソースの newlisp-x.x.x/examples/ ディレクトリにある udp-server.lspudp-client.lsp を見てください。
Both, the sender and the receiver have to issue net-listen commands for UDP mode. Not for listening as in TCP/IP protocol communications, but to create the socket bound to the port and address. For a complete example see the files udp-server.lsp and udp-client.lsp in the newlisp-x.x.x/examples/ directory of the source distribution.

この場合、net-receive は送信側のアドレスとポートの情報を返さないので使えません。 UDP 通信では、通信が行われるソケットではなく 、データパケット自身に送信側のアドレスを含みます。 net-receive を TCP/IP にも使うことができます。
Note that net-receive could not be used in this case because it does not return the sender's address and port information, which are required to talk back. In UDP communications, the data packet itself contains the address of the sender, not the socket over which communication takes place. net-receive can also be used for TCP/IP communications.

"udp" オプションの関数 net-connect と 開いている接続で UDP データ・パケットを送信する関数 net-send-to も見てください。
See also the net-connect function with the "udp" option and the net-send-to function for sending UDP data packets over open connections.

ブロッキング の短い UDP 処理には、関数 net-send-udpnet-receive-udp を見てください。
For blocking short UDP transactions, see the net-send-udp and net-receive-udp functions.



net-receive-udp

syntax: (net-receive-udp int-port int-maxsize [int-microsec [str-addr-if]])

ポート int-port 上のユーザ・データグラム・プロトコル (UDP) パケットを受信し、 int-maxsize バイト読み取ります。 tt>net-receive-udp が int-maxsize バイトより多く受信した場合、int-maxsize を超えるバイトを破棄し、MS Windows では nil を返します。 net-receive-udp は、データが届くか、オプションのタイムアウト値 int-microsec に達するまでブロックします。 データの送信側と受信側で通信が成立する前に、net-receive-udp 宣言文が発行されている必要があります。
Receives a User Datagram Protocol (UDP) packet on port int-port, reading int-maxsize bytes. If more than int-maxsize bytes are received, bytes over int-maxsize are discarded on Linux/BSD; on MS Windows, net-receive-udp returns nil. net-receive-udp blocks until a datagram arrives or the optional timeout value in int-microsec expires. When setting up communications between datagram sender and receiver, the net-receive-udp statement must be set up first.

net-listennet-connect を使って、前もって準備しておく必要はありません。
No previous setup using net-listen or net-connect is necessary.

net-receive-udp が返すリストには、UDP パケットの文字列とそれに続けて、送信側が使った IP 番号とポートの文字列が入っています。
net-receive-udp returns a list containing a string of the UDP packet followed by a string containing the sender's IP number and the port used.

;; wait for datagram with maximum 20 bytes 
(net-receive-udp 10001 20) 

;; or
(net-receive-udp 10001 20 5000000)  ; wait for max 5 seconds
		  
;; executed on remote computer
(net-send-udp "nuevatec.com" 1001 "Hello")   4 

;; returned from the net-receive-udp statement
 ("Hello" "128.121.96.1" 3312)  

;; sending binary information
(net-send-udp "ahost.com" 2222 (pack "c c c c" 0 1 2 3))  
 4 

;; extracting the received info
(set 'buff (first (net-receive-udp 2222 10)))   

(print (unpack "c c c c" buff))   (0 1 2 3)

データ送信用関数 net-send-udp や、バイナリ・データのパック用関数 pack とアンパック用関数 unpack も見てください。
See also the net-send-udp function for sending datagrams and the pack and unpack functions for packing and unpacking binary information.

一個以上のインターフェイス・カードを持つコンピュータ上で、指定されたアドレスを待ち受け(listen)るために、オプションでインターフェイス IP アドレスまたは名前を str-addr-if に指定できます。 str-addr-if を指定する時は、タイムアウト int-wait の指定も必要です。
To listen on a specified address on computers with more than one interface card, an interface IP address or name can be optionally specified in str-addr-if. When specifying str-addr-if, a timeout must also be specified in int-wait.

もう一つの方法として、ノン・ブロッキング・データ交換を可能にする "udp" オプションの net-listennet-connectnet-receive-fromnet-send-to と一緒に使っても、UDP 通信を用意できます。
As an alternative, UDP communication can be set up using net-listen, or net-connect together with the "udp" option to make non-blocking data exchange possible with net-receive-from and net-send-to.



net-select

syntax: (net-select int-socket str-mode int-micro-seconds)
syntax: (net-select list-sockets str-mode int-micro-seconds)

第一形式の net-select は、int-socket で指定された一パケットの状態を検出します。 str-mode 次第で、ソケットが読み取りまたは書き込みが用意されているとか、エラー条件を持っているとかをチェックします。 タイムアウト値は int-micro-seconds で指定します。
In the first form, net-select finds out about the status of one socket specified in int-socket. Depending on str-mode, the socket can be checked if it is ready for reading or writing, or if the socket has an error condition. A timeout value is specified in int-micro-seconds.

第二構文の net-select は、list-sockets のソケット・リストをチェックできます。
In the second syntax, net-select can check for a list of sockets in list-sockets.

str-mode には、次のような値が与えられます:
読み取り状態か、受け入れ状態かどうかのチェックには、"read""r"
書き込み状態かどうかのチェックには、"write""w"
エラー状態のチェックには、"exception""e"
The following value can be given for str-mode:
"read" or "r" to check if ready for reading or accepting.
"write" or "w" to check if ready for writing.
"exception" or "e" to check for an error condition.

関数 net-select を使えば、受信・送信・受付操作をブロック無しで処理できます。 net-select は、ソケットが準備されるまで int-micro-seconds で指定された時間待ち、準備状態によって truenil を返します。 セレクト・ループ中、他のプログラム部分を実行可能です。 エラー発生時には、net-error が設定されます。 int-micro-seconds-1 が指定された時、net-select はタイムアウトしません。
Read, send, or accept operations can be handled without blocking by using the net-select function. net-select waits for a socket to be ready for the value given in int-micro-seconds, then returns true or nil depending on the readiness of the socket. During the select loop, other portions of the program can run. On error, net-error is set. When -1 is specified for int-micro-seconds, net-select will never time out.

(set 'listen-socket (net-listen 1001))

;; wait for connection
(while (not (net-select listen-socket "read" 1000))
    (if (net-error) (print (net-error))))

(set 'connection (net-accept listen-socket))
(net-send connection "hello")

;; wait for incoming message
(while (not (net-select connection "read" 1000))
    (do-something)) 

(net-receive connection buff 1024)

net-select を使うことで、いくつかの待ち受け(listen)と接続ソケットを監視でき、複数の接続が処理できます。 ソケット・リストを使った時、net-select は準備の整ったソケットのリストを返します。 続く例は、二つのソケットを待ち受け(listen)、その接続の受け入れとサービスを続けます:
When net-select is used, several listen and connection sockets can be watched, and multiple connections can be handled. When used with a list of sockets, net-select will return a list of ready sockets. The following example would listen on two sockets and continue accepting and servicing connections:

(set 'listen-list '(1001 1002))

; accept-connection, read-connection and write-connection
; are user defined functions

(while (not (net-error))
    (dolist (conn (net-select listen-list "r" 1000))
    (accept-connection conn))  ; build an accept-list

    (dolist (conn (net-select accept-list "r" 1000))
    (read-connection conn))    ; read on connected sockets

    (dolist (conn (net-select accept-list "w" 1000))
    (write-connection conn)))  ; write on connected sockets

第二構文では、テストを通った全てのソケットを含むリストが返り、タイムアウト時は空のリストが返ります。 エラー発生時は、net-error が設定されます。
In the second syntax, a list is returned containing all the sockets that passed the test; if timeout occurred, an empty list is returned. An error causes net-error to be set.

存在しないソケットを net-select へ提供することはエラーを発生させ、net-error が設定されることに注意してください。
Note that supplying a nonexistent socket to net-select will cause an error to be set in net-error.



net-send

syntax: (net-send int-socket str-buffer [int-num-bytes])

str-buffer の内容を int-socket で指定された接続に送ります。 int-num-bytes を指定すれば、int-num-bytes までが送られます。 int-num-bytes を指定しなければ、全内容が送られます。 net-send は、送信したバイト数か、失敗した時の nil を返します。
Sends the contents of str-buffer on the connection specified by int-socket. If int-num-bytes is specified, up to int-num-bytes are sent. If int-num-bytes is not specified, the entire contents will be sent. net-send returns the number of bytes sent or nil on failure.

失敗時にエラー情報を得るには、net-error を使ってください。
On failure, use net-error to get more error information.

(set 'buf "hello there")

(net-send sock buf)        11
(net-send sock buf 5)      5

(net-send sock "bye bye")  7

最初の net-send は文字列 "hello there" を送り、二番目の net-send は文字列 "hello" のみを送ります。
The first net-send sends the string "hello there", while the second net-send sends only the string "hello".



net-send-to

syntax: (net-send-to str-remotehost int-remoteport str-buffer int-socket)

UDP か TCP/IP 通信のどちらかで使うことができます。 前もって、関数net-connectnet-listenint-socket のソケットが開かれている必要が有ります。 関数 net-listennet-connect"udp" オプションで開いているなら、UDP ソケットを生成するだけで待ち受け(listen)や接続に使われていません。 str-remotehost のホストは、ホスト名か IP 番号文字列のどちらかで指定できます。
Can be used for either UDP or TCP/IP communications. The socket in int-socket must have previously been opened with a net-connect or net-listen function. If the opening functions was used with the "udp" option, net-listen or net-connect are not used to listen or to connect but only to create the UDP socket. The host in str-remotehost can be specified either as a hostname or as an IP-number string.

net-connect と一緒に net-send-to を使う時は、どちらかの関数一つだけにリモート・ホストを指定すべきです。 もう片方には、空の文字列を指定して、アドレスを切り離すのです。
When using net-connect together with net-send-to, then only one of the functions should specify the remote host. The other should leave the address as an empty string.

;;;;;;;;;;;;;;;;;; UDP server
(set 'socket (net-listen 10001 "" "udp"))
(if socket (println "server listening on port " 10001)
       (println (net-error)))
(while (not (net-error))
   (set 'msg (net-receive-from socket 255))
   (println "-> " msg)
   (net-send-to (nth 1 msg) (nth 2 msg) 
                (upper-case (first msg)) socket))

;;;;;;;;;;;;;;;;;; UDP client
(set 'socket (net-listen 10002 "" "udp"))
(if (not socket) (println (net-error)))
(while (not (net-error))
   (print "> ")
   (net-send-to "127.0.0.1" 10001 (read-line) socket)
   (net-receive socket buff 255)
   (println "-> " buff))

どちらの例でも、クライアントとサーバー双方が送受信用の UDP ソケット生成に net-listen を使っています。 サーバーは受け取ったメッセージからクライアントのアドレスとポートを抜き出し、それを net-send-to 宣言文に使っています。
In the examples both, the client and the server use net-listen to create the UDP socket for sending and receiving. The server extracts the client address and port from the message received and uses it in the net-send-to statement.

関数 net-receive-from と関数 net-listen"udp" オプションも見てください。
See also the net-receive-from function and the net-listen function with the "udp" option.

ブロッキングの短い UDP 処理には、net-send-udpnet-receive-udp を使ってください。
For blocking short UDP transactions use net-send-udp and net-receive-udp.



net-send-udp

syntax: (net-send-udp str-remotehost int-remoteport str-buffer [bool])

str-remotehost で指定されるホストと int-remoteport のポートにユーザ・データグラム・プロトコル (UDP) を送ります。 送信するデータは str-buffer の中です。
Sends a User Datagram Protocol (UDP) to the host specified in str-remotehost and to the port in int-remoteport. The data sent is in str-buffer.

IPv4 システム上では UDP パケットの理論的な最大データ・サイズが 64K から IP レイヤー分を引いた値ですが、多くの Unix 流派ではそれよりもかなり少なくなります。 macOS、BSD、Linux では 8k が安全なサイズでしょう。
The theoretical maximum data size of a UDP packet on an IPv4 system is 64K minus IP layer overhead, but much smaller on most Unix flavors. 8k seems to be a safe size on macOS, BSDs and Linux.

net-connectnet-listen を使って、前もってセットアップしておくことは、必要ありません。 net-send-udp は直ちに送信したバイト数を返し、使ったソケットを閉じます。 受信側で net-receive-udp 宣言文が待っていないと、データは失われます。 不確かな接続上でのデータ通信をする時に伝送を確実にするためには、送信側と受信側間で簡単な手順のセットアップが推奨されます。 UDP 通信それ自体は、TCP/IP のように伝送の信頼性を保証しません。
No previous setup using net-connect or net-listen is necessary. net-send-udp returns immediately with the number of bytes sent and closes the socket used. If no net-receive-udp statement is waiting at the receiving side, the datagram sent is lost. When using datagram communications over insecure connections, setting up a simple protocol between sender and receiver is recommended for ensuring delivery. UDP communication by itself does not guarantee reliable delivery as TCP/IP does.

(net-send-udp "somehost.com" 3333 "Hello")   5

net-send-udp はバイナリ・データの送信にも適しています(例えば、ゼロ・キャラクタやその他、表示できないバイト等)。 もっとわかり易い例は、net-receive-udp で見てください。
net-send-udp is also suitable for sending binary information (e.g., the zero character or other non-visible bytes). For a more comprehensive example, see net-receive-udp.

オプションの booltrue を指定するか nil 以外に評価される式を指定すると、送信ソケットをブロードキャスト・モードにできます。
Optionally, the sending socket can be put in broadcast mode by specifying true or any expression not evaluating to nil in bool:

(net-send-udp "192.168.1.255" 2000 "Hello" true)   5

(訳注:上の例では、)UDP が 192.168.1 ネットワーク上の全ノードに送信されます。 いくつかのオペレーティング・システムでは、booltrue 無しでもネットワーク・マスク 255 を送信することで、ブロードキャスト・モードが可能になります。
The UDP will be sent to all nodes on the 192.168.1 network. Note that on some operating systems, sending the network mask 255 without the bool true option will enable broadcast mode.

他の方法として、"udp" オプションを使った関数 net-connect を——関数 net-send-to と一緒に使うことで——ノン・ブロッキング状態での UDP 待ち受け(listen)への通信に使えます。
As an alternative, the net-connect function using the "udp" option—together with the net-send-to function—can be used to talk to a UDP listener in a non-blocking fashion.



net-service

syntax: (net-service str-service str-protocol)
syntax: (net-service int-port str-protocol)

第一構文の net-service は、services のデータベースを検索して、そのサービスの標準ポート番号を返します。 (訳注: C 関数 getservbyname 相当。参考まで
In the first syntax net-service makes a lookup in the services database and returns the standard port number for this service.

第二構文では、サービス名を検索するために サービス・ポートを int-port に与えます。
In the second syntax a service port is supplied in int-port to look up the service name.

失敗時は nil を返します。
Returns nil on failure.

; get the port number from the name
(net-service "ftp" "tcp")        21
(net-service "http" "tcp")       80
(net-service "net-eval" "tcp")   4711  ; if configured

; get the service name from the port number
(net-service 22 "tcp")           "ssh"


net-sessions

syntax: (net-sessions)

アクティブな待ち受け(listen)や接続ソケットのリストを返します。
Returns a list of active listening and connection sockets.



new

syntax: (new context-source sym-context-target [bool])
syntax: (new context-source)

コンテキスト context-sourcesym-context-target にコピーされます。 目標コンテキストが存在しなければ、context-source にあるのと同じ名前の変数群とユーザ定義関数と持つ新コンテキストが作成されます(訳注:ただし、デフォルト・ファンクタ は目標コンテキスト名になります)。 目標コンテキストが既に存在するなら、新規のシンボルと定義が付け加えられます。 存在するシンボルは、bool の式が nil 以外に評価される時のみ上書きされ、それ以外では、そのままの内容で残ります(訳注:bool 式次第で、デフォルト・ファンクタ も上書きされます)。 これは、コンテキスト・オブジェクトの mixins を可能にします。 new は、MAIN ではない目標コンテキストを返します。
The context context-source is copied to sym-context-target. If the target context does not exist, a new context with the same variable names and user-defined functions as in context-source is created. If the target context already exists, then new symbols and definitions are added. Existing symbols are only overwritten when the expression in bool evaluates to anything other than nil; otherwise, the content of existing symbols will remain. This makes mixins of context objects possible. new returns the target context, which cannot be MAIN.

第二構文では、 context-source の既存のコンテキストが目標コンテキストとして現在のコンテキストにコピーされます。 (訳注:第一構文で sym-context-target に MAIN が使えないのと同様に、第二構文は MAIN コンテキスト上では使えません。)
In the second syntax, the existing context in context-source gets copied into the current context as the target context.

元となるコンテキスト上の全てのシンボルへの参照は、目標コンテキスト上での参照に移植されます。 この方法で(訳注:コピーされた)元のコンテキスト上のシンボルを参照している全ての関数とデータ構造は、目標コンテキスト上のシンボルを参照します。
All references to symbols in the originating context will be translated to references in the target context. This way, all functions and data structures referring to symbols in the original context will now refer to symbols in the target context.

(new CTX 'CTX-2)   CTX-2   

;; force overwrite of existing symbols
(new CTX MyCTX true)   MyCTX   

例の一行目は、元のコンテキストと厳密に同じ構造を持つ CTX-2 と呼ばれる新規コンテキストを生成します。 コンテキストはそれ自身に評価されるので、CTX にクォートがありませんが、 CTX-2 はまだ存在しないので、クォートであることが必要であることに注意してください。
The first line in the example creates a new context called CTX-2 that has the exact same structure as the original one. Note that CTX is not quoted because contexts evaluate to themselves, but CTX-2 must be quoted because it does not exist yet.

二行目は、MyCTXCTX を併合します。 MyCTX に同じ名前で存在するシンボルは、上書きされます。 MyCTX は既に存在するので、コンテキスト・シンボルの前のクォートは省略可能です。
The second line merges the context CTX into MyCTX. Any existing symbols of the same name in MyCTX will be overwritten. Because MyCTX already exists, the quote before the context symbol can be omitted.

コンテキスト中のシンボルを明示的に記述する必要はありませんが、変数として含められます。
Context symbols need not be mentioned explicitly, but they can be contained in variables:

(set 'foo:x 123)
(set 'bar:y 999)

(set 'ctxa foo)
(set 'ctxb bar)

(new ctxa ctxb)  ; from foo to bar

bar:x   123  ; x has been added to bar
bar:y   999)

例では、コンテキストを変数で参照し、コンテキスト barfoo を併合しています。
The example refers to contexts in variables and merges context foo into bar.

完全なコンテキストの代わりに、単一関数の移植や併合用の関数 def-new も見てください。 new のよりわかりやすい例については、関数 context を見てください。
See also the function def-new for moving and merging single functions instead of entire contexts. See the context function for a more comprehensive example of new.



nil?

syntax: (nil? exp)

exp の式が nil に評価されるなら、nil?true を返し、それ以外では nil を返します。
If the expression in exp evaluates to nil, then nil? returns true; otherwise, it returns nil.

(map nil? '(x nil  1 nil "hi" ()))
 (nil true nil true nil nil)

(nil? nil)   true
(nil? '())   nil

; nil? means strictly nil
(nil? (not '()))   nil

述語 nil? は、nil と空のリスト () を区別するのに使えます。
The nil? predicate is useful for distinguishing between nil and the empty list ().

nil?厳密に nil を示す一方で、true?nil でも空のリスト () でもない全てを示します。
Note that nil? means strictly nil while true? means everything not nil or the empty list ().



normal

syntax: (normal float-mean float-stdev int-n)
syntax: (normal float-mean float-stdev)

第一形式 の normal は、平均値 float-mean と 標準偏差 float-stdev でランダムかつ継続的に分散された長さ int-n の浮動小数点数のリストを返します。 内部のランダム生成は、関数 seed を使って種 (seed) を設定されます。
In the first form, normal returns a list of length int-n of random, continuously distributed floating point numbers with a mean of float-mean and a standard deviation of float-stdev. The random generator used internally can be seeded using the seed function.

(normal 10 3 10)
 (7 6.563476562 11.93945312 6.153320312 9.98828125
7.984375 10.17871094 6.58984375 9.42578125 12.11230469)

第二形式の normal は、一個の標準分散値を返します(訳注:つまり、戻り値はリストではありません):
In the second form, normal returns a single normal distributed floating point number:

(normal 1 0.2)  0.646875

パラメータなしの時、normal は平均を 0.0、標準偏差を 1.0 と見なします。
When no parameters are given, normal assumes a mean of 0.0 and a standard deviation of 1.0.

均等に分散された数値用の関数 randomrand、式のリストの中からランダムに評価する amb、擬似ランダム数生成に異なる開始点を設定する seed も見てください。
See also the random and rand functions for evenly distributed numbers, amb for randomizing evaluation in a list of expressions, and seed for setting a different start point for pseudo random number generation.



not

syntax: (not exp)

expnil か空リスト () に評価されたなら、 true が返り、それ以外では nil が返ります。
If exp evaluates to nil or the empty list (), then true is returned; otherwise, nil is returned.

(not true)             nil
(not nil)              true
(not '())              true
(not (< 1 10))         nil
(not (not (< 1 10)))   true


now

syntax: (now [int-minutes-offset [int-index]])

現在の日付と時刻の情報を整数のリストで返します。 オプションの int-minutes-offset に、タイム・ゾーンのオフセットを分単位で指定できます。 このオプションは、日付に分ける前の時間を前後にずらします。
Returns information about the current date and time as a list of integers. An optional time-zone offset can be specified in minutes in int-minutes-offset. This causes the time to be shifted forward or backward in time, before being split into separate date values.

int-index オプションのリスト・インデックスにより、now は結果リストから指定された要素を返します。
An optional list-index in int-index makes now return a specific member in the result list.

(now)        (2002 2 27 18 21 30 140000 57 3 -300 0)
(now 0 -2)   -300 ; minutes west of GMT


(date-value (now))   1014834090

数値は、次のように表現されています:
The numbers represent the following date-time fields:

formatdescription

year
グレゴリオ暦
Gregorian calendar

month
(1–12)

day
(1–31)

hour
協定世界時上の (0–23)
(0–23) UTC()

minute
(0–59)

second
(0–59)
マイクロ秒
microsecond
(0–999999) OS の仕様によっては、ミリ秒単位の解像度
(0–999999) OS-specific, millisecond resolution
年間通算日
day of current year
一月一日が 1
Jan 1st is 1
週の曜日
day of current week
月曜から始まる (1–7)
(1–7) starting Monday
タイムゾーンのオフセット(分単位)
time zone offset in minutes
グリニッジ標準時から西回りで、夏時間のオフセットを含む(訳注:(now (now 0 -2)) で現タイムゾーンの現在の日時)
west of GMT including daylight savings bias
夏時間の型
daylight savings time type
Linux/Unix では (0–6)、MS Windows では (0–2)
(0–6) on Linux/Unix or (0–2) on MS Windows

二つ目の例は、協定世界時 (UTC) で1970年1月1日からの秒数を返しています。
The second example returns the Coordinated Universal Time (UTC) time value of seconds after January 1, 1970.

0 ~ 23 の範囲でUTC 上の hour が与えられますが、ローカル・タイム・ゾーンの補正は行われません。 microsecond の精度は、オペレーティングシステムやプラットフォーム次第です。 いくつかのプラットフォームでは、 microsecond の下3桁は常に 0(ゼロ)になります。
Ranging from 0 to 23, hours are given in UTC and are not adjusted for the local time zone. The resolution of the microseconds field depends on the operating system and platform. On some platforms, the last three digits of the microseconds field are always 0 (zero).

日付と時刻表記に関する国際規格 ISO 8601 に合わせて、"day of the week" の値は月曜日を 1 として開始します。
The "day of the week" field starts with 1 on Monday conforming to the ISO 8601 international standard for date and time representation.

いくつかのプラットフォームでは、夏時間フラグはアクティブでなく、夏時間期間 (dst) 中でも 0(ゼロ)を返します
On some platforms, the daylight savings time flag is not active and returns 0 (zero) even during daylight savings time (dst).

地域によって夏時間 (dst) の型は、1 ~ 6 までの異なる値を持ちます:
Depending on the geographical area, the daylight savings time type (dst) has a different value from 1 to 6:

UNIX typearea
0not on daylight savings
1USA style dst
2Australian style daylight savings
3Western European daylight savings
4Middle European daylight savings
5Eastern European daylight savings
6Canada dst

Windows type
0Daylight saving time is not used
1Standard date time range is used
2Daylight date time range is used (daylight savings active)

関数 datedate-listdate-parsedate-valuetimetime-of-day も見てください。
See also the date, date-list, date-parse, date-value, time, and time-of-day functions.



nper

syntax: (nper num-interest num-pmt num-pv [num-fv [int-type]])

num-pv のローンを固定利率 num-interest と支払額 num-pmt で支払う時に必要な支払回数を計算します。 支払いが期間の終わりなら int-type0(ゼロ)にするか省略し、支払いが期間の最初なら int-type を 1 にします。(訳注:int-type を指定する時には、num-fv の指定(デフォルト値 0.0)も必要です)
Calculates the number of payments required to pay a loan of num-pv with a constant interest rate of num-interest and payment num-pmt. If payment is at the end of the period, int-type is 0 (zero) or int-type is omitted; for payment at the beginning of each period, int-type is 1.

(nper (div 0.07 12) 775.30 -100000)   239.9992828

例では、100,000ドルのローンを年利 7%、月々 775.3 ドル支払う場合に必要な支払月数を計算しています。
The example calculates the number of monthly payments required to pay a loan of $100,000 at a yearly interest rate of 7 percent with payments of $775.30.

(訳例:年利 0.07%、月々 775.3 ドル支払いで 100,000 ドルを貯めるに必要な月数の計算は、
> (nper (div 0.0007 12) -775.30 0 100000)
128.503268
となります。 )

関数 fvirrnpvpmtpv も見てください。
See also the fv, irr, npv, pmt, and pv functions.



npv

syntax: (npv num-interest list-values)

固定利率 num-interest と未来の一連の投資および配当 list-values から、投資の総現在価値を計算します。 list-values 中に投資額を負の数で表し、配当は正の数で表します。
Calculates the net present value of an investment with a fixed interest rate num-interest and a series of future payments and income in list-values. Payments are represented by negative values in list-values, while income is represented by positive values in list-values.

(npv 0.1 '(1000 1000 1000)) 
 2486.851991

(npv 0.1 '(-2486.851991 1000 1000 1000)) 
 -1.434386832e-08  ; ~ 0.0 (zero)

例によれば、(訳注:年利10%での)初期投資2,481.85ドルは、一年後、二年後、三年後の年末に 1,000ドルの配当なら許されるでしょう。
In the example, an initial investment of $2,481.85 would allow for an income of $1,000 after the end of the first, second, and third years.

関数 fvirrnperpmtpv も見てください。
See also the fv, irr, nper, pmt, and pv functions.



nth utf8

syntax: (nth int-index list)
syntax: (nth int-index array)
syntax: (nth int-index str)

syntax: (nth list-indices list)
syntax: (nth list-indices array)

第一構文グループの nth はインデックス int-index を使って、list, array, str からインデックスで見つかる要素を返します。 文字列、リスト、アレイの要素指定 も見てください。
In the first syntax group nth uses int-index an index into the list, array or str found and returning the element found at that index. See also Indexing elements of strings and lists.

入れ子構造のリストやアレイの要素を再帰的にアクセスするために、複数のインデックスを指定するかもしれません。 その際、入れ子レベルより多いインデックスは無視されます。 複数のインデックスを指定する時は、第二構文グループで示されているようにリストで指定する必要があります。
Multiple indices may be specified to recursively access elements in nested lists or arrays. If there are more indices than nesting levels, the extra indices are ignored. When multiple indices are used, they must be put in a list as shown in the second syntax group.

(set 'L '(a b c))
(nth 0 L)     a
; or simply
(L 0)  a

(set 'names '(john martha robert alex)) 
 (john martha robert alex)

(nth 2 names)     robert
; or simply
(names 2)         robert

(names -1)        alex


; multiple indices
(set 'persons '((john 30) (martha 120) ((john doe) 17)))

(persons 1 1)            120

(nth '(2 0 1) persons)   doe

; or simply
(persons 2 0 1)         doe

; multiple indices in a vector
(set 'v '(2 0 1))
(persons v)        doe
(nth v persons)    doe

; negative indices
(persons -2 0)     martha

; out-of-bounds indices cause error
(persons 10)   ERR: list index out of bounds
(person -5)    ERR: list index out of bounds

リスト L は、デフォルト・ファンクタ L:L のコンテキストでも可能です。 これは、リストの参照渡しを可能にします:
The list L can be the context of the default functor L:L. This allows lists passed by reference:

(set 'L:L '(a b c d e f g))

(define (second ctx)
	(nth 1 ctx))

(reverse L)  (g f e d c b a)
L:L  (g f e d c b a)

;; passing the list in L:L by reference
(second L)    b

;; passing the list in L:L by value
(second L:L)  b

参照渡しは高速で大きなリストでも少ないメモリで済みますので、数百より多い要素のリストでは使うべきです。
Reference passing is faster and uses less memory in big lists and should be used on lists with more than a few hundred items.

nth暗黙の要素指定 版は newLISP 構文を壊すものではなく、newLISP 構文の論理的拡張は組込関数やラムダ式よりもデータ型で規定されると理解すべきことに注目してください。 s式のファンクタ(関数オブジェクト)位置にあるリストは、続くインデックス引数を使った自己インデックス機能と解釈されます。
Note that the implicit indexing version of nth is not breaking newLISP syntax rules but should be understood as a logical expansion of newLISP syntax rules to other data types than built-in functions or lambda expressions. A list in the functor position of an s-expression assumes self-indexing functionality using the index arguments following.

暗黙のインデックス構文形式は速いですが、同じ状況下では、明示的に nth を使った形式の方が可読性の良いものになります。
The implicit indexed syntax forms are faster but the other form with an explicit nth may be more readable in some situations.

nth は、リストにと同様に arrays に対しても動作します:
nth works on arrays just like it does on lists:

(set 'aArray (array 2 3 '(a b c d e f))) 
 ((a b c) (d e f))
(nth 1 aArray)        (d e f)
(aArray 1)            (d e f)

(nth '(1 0) aArray)     d
(aArray 1 0)            d
(aArray '(1 0))         d

(set 'vec '(1 0))
(aArray vec)            d

文字列版の nth は、str から int-index 位置の文字を見つけ出し、文字列として返します。
In the String version, nth returns the character found at the position int-index in str and returns it as a string.

(nth  0 "newLISP")    "n"

("newLISP" 0)         "n"

("newLISP" -1)        "P"

UTF-8 版 newLISP を使っている時、nth はバイト境界ではなく、文字境界で作用することに注意してください。 ASCII やバイナリ文字列に1バイト境界でアクセスするためには、slice を使います。
Note that nth works on character boundaries rather than byte boundaries when using the UTF-8–enabled version of newLISP. To access ASCII and binary string buffers on single byte boundaries use slice.

多次元リストやアレイを変更する setf やリストを変更する pushpop も見てください。
See also setf for modifying multidimensional lists and arrays and push and pop for modifying lists.



null?

syntax: (null? exp)

式が nil、空リスト ()、空文字列 ""NaN (not a number)、0(ゼロ)のいずれかに評価されるかどうかをチェックし、そうであれば true を返します。 それ以外の全てでは、null?nil を返します。 述語 null? は、filterclean と連携して、newLISP 操作の出力をチェックするために使えます。
Checks if an expression evaluates to nil, the empty list (), the empty string "", NaN (not a number), or 0 (zero), in which case it returns true. In all other cases, null? returns nil. The predicate null? is useful in conjunction with the functions filter or clean to check the outcome of other newLISP operations.

(set 'x (sqrt -1))  NaN ; or nan on UNIX
(null? x)  true

(map null? '(1 0 0.0 2 "hello" "" (a b c) () true))
 (nil true true nil nil true nil true nil) 

(filter null? '(1 0 2 0.0 "hello" "" (a b c) () nil true)) 
 (0 0 "" () nil)

(clean null? '(1 0 2 0.0 "hello" "" (a b c) () nil true))
 (1 2 "hello" (a b c) true)
(訳例:
> [cmd]
(let (NaN (sqrt -1) INF (div 1 0))
  (let (lst (list 0 0.0 NaN INF ""  '() nil))
    (println "list  " lst)
    (println "true? " (map true? lst))
    (println "not   " (map not   lst))
    (println "null? " (map null? lst))
    (println "nil?  " (map nil?  lst))
    (print   "list  ") lst))
[/cmd]
list  (0 0 nan inf "" () nil)
true? (true true true true true nil nil)
not   (nil nil nil nil nil true true)
null? (true true true nil true true true)
nil?  (nil nil nil nil nil nil true)
list  (0 0 nan inf "" () nil)
> 

述語 empty?nil?zero? も見てください。
See also the predicates empty?, nil? and zero?.



number?  bigint

syntax: (number? exp)

exp が浮動小数点数か整数に評価されたなら true が返り、それ以外では nil が返ります。
true is returned only if exp evaluates to a floating point number or an integer; otherwise, nil is returned.

(set 'x 1.23)
(set 'y 456)
(number? x)       true
(number? y)       true
(number? "678")   nil  
(訳例:
> (sqrt -1)
nan
> (number? (sqrt -1))
true
> (div 1 0)
inf
> (number? (div 1 0))
true
 NaNINF の型は、浮動小数点数です。)

数値型を特定するテスト関数 float?integer? も見てください。
See the functions float? and integer? to test for a specific number type.



odd?  bigint

syntax: (odd? int-number)

整数値の偶奇をチェックします。 数値が 2割り切れ ないなら、それは奇数 です。 int-number に浮動小数点数が渡されると、最初に小数部分が切り捨てられ、整数に変換されます。
Checks the parity of an integer number. If the number is not even divisible by 2, it has odd parity. When a floating point number is passed for int-number, it will be converted first to an integer by cutting off its fractional part.

(odd? 123)   true
(odd? 8)     nil
(odd? 8.7)   nil

整数が 2 で割り切れる偶数かどうかのチェックには、even? を使ってください。
Use even? to check if an integer is even, divisible by 2.



open

syntax: (open str-path-file str-access-mode [str-option])

str-path-file はファイル名、str-access-mode はファイル・アクセス・モードを指定する文字列です。 open は整数値を返し、それがファイル・ハンドルとなって、以下に続くファイルの読み書き操作で使います。 失敗時、opennil を返します。 "write" アクセス・モードでは、ファイルが存在しない時は作成します。また、ファイルが存在時は長さを 0(ゼロ)バイトに切り詰めます。(訳注:つまり、新規ファイルと同じになります)
The str-path-file is a file name, and str-access-mode is a string specifying the file access mode. open returns an integer, which is a file handle to be used on subsequent read or write operations on the file. On failure, open returns nil. The access mode "write" creates the file if it doesn't exist, or it truncates an existing file to 0 (zero) bytes in length.

以下の文字列が所定のアクセス・モードです:
The following strings are legal access modes:

リード・オンリー・アクセス用  "read" または "r"
ライト・オンリー・アクセス用  "write" or "w"
リード/ライト・アクセス用   "update" or "u"
リード/追加ライト・アクセス用 "append" or "a"
"read" or "r" for read only access
"write" or "w" for write only access
"update" or "u" for read/write access
"append" or "a" for append read/write access


(device (open "newfile.data" "write"))   5
(print "hello world\n")   "hello world"
(close (device))          5

(set 'aFile (open "newfile.data" "read"))
(seek aFile 6)
(set 'inChar (read-char aFile))
(print inChar "\n")
(close aFile)

最初の例では print のデバイス設定にopen を使い、文字列 "hello world" をファイルnewfile.data に書き込んでいます。 二番目の例では、同ファイルのオフセット 6 のバイト値( 'w'アスキー値、 119)を読み取っています。 (device) に対して close を使う事は、device を自動的に 0(ゼロ)にリセットするので注意してください。
The first example uses open to set the device for print and writes the word "hello world" into the file newfile.data. The second example reads a byte value at offset 6 in the same file (the ASCII value of 'w' is 119). Note that using close on (device) automatically resets device to 0 (zero).

tt>"read" や "write" オプションの後に、str-option オプション として "non-block""n" を指定できます。 これは Unix システムでのみで有効で、名前付きパイプ を開くが名前付きパイプ上の I/O の実行を要求されないノン・ブロッキング・モードに使えます。
As an additional str-option, "non-block" or "n" can be specified after the "read" or "write" option. Only available on Unix systems, non-blocking mode can be useful when opening named pipes but is not required to perform I/O on named pipes.



or

syntax: (or exp-1 [exp-2 ... ])

exp-x の式群を nil か 空リスト () 以外に評価されるまで左から右へ評価します。 その結果が or 式の戻り値になります。
Evaluates expressions exp-x from left to right until finding a result that does not evaluate to nil or the empty list (). The result is the return value of the or expression.

(set 'x 10)
(or (> x 100) (= x 10))           true
(or "hello" (> x 100) (= x 10))   "hello"
(or '())                          ()
(or true)                         true
(or)                              nil


ostype

syntax: ostype

newLISP の走っているオペレーティング・システム名が入っている組込定数です。
ostype is a built-in system constant containing the name of the operating system newLISP is running on.

ostype   "Windows"

次の文字列の中の一つが返ります:"Linux", "BSD", "OSX", "Tru64Unix", "Solaris", "SunOS", "Windows", "Cygwin","OS/2"
One of the following strings is returned: "Linux", "BSD", "OSX", "Tru64Unix", "Solaris", "SunOS", "Windows", "Cygwin", or "OS/2".

ostype は、プラットフォームに依存したコードを書く時に使えます:
ostype can be used to write platform-independent code:

(if 
    (= ostype "Linux") (import "libz.so")
    (= ostype "BSD") (import "libz.so")
    (= ostype "OSX") (import "libz.dylib")
    ...
    (println "cannot import libz on this platform")
)

newLISP の走っている現環境について多く知るには、sys-info を使ってください。
Use sys-info to learn more about the current flavor of newLISP running.

他の組込システム変数やシンボルの表は、付録の System Symbols and Constants の章で見てください。
For a table of other built-in system variables and symbols see the chapter System Symbols and Constants in the appendix.



pack

syntax: (pack str-format [exp-1 [exp-2 ... ]])
syntax: (pack str-format [list])

syntax: (pack struct [exp-1 [exp-2 ... ]])
syntax: (pack struct [list])

一個以上の式群 (exp-1exp-n) をフォーマット文字列 str-format に指定されたバイナリ・フォーマットでパックし、文字列バッファに入ったバイナリ構造体を返します。 アンパックには、対となる関数 unpack が使えます。 引数の式群は list で与えることもできます(訳注:第二構文)。 packunpack は、バイナリ・ファイルの読み書き(readwrite 参照)や import で導入された C 関数の戻り値からバイナリ構造体をアンパックする時に役に立ちます。
When the first parameter is a string, pack packs one or more expressions (exp-1 to exp-n) into a binary format specified in the format string str-format, and returning the binary structure in a string buffer. The symmetrical unpack function is used for unpacking. The expression arguments can also be given in a list. pack and unpack are useful when reading and writing binary files (see read and write) or when unpacking binary structures from return values of imported C functions using import.

第一パラメータが struct 定義シンボルの時、packstruct で定義されたフォーマットを使います。 str-format を使った pack は、指定された文字の通りにパックします。 一方、struct を使った pack は、データ型と要素の順序とCPUアーキテクチャに従って一直線に詰められたバイト群である構造体に入れていきます。 詳細は関数 struct を参照してください。
When the first parameter is the symbol of a struct definition, pack uses the format as specified in struct. While pack with str-format literally packs as specified, pack with struct will insert structure aligning pad-bytes depending on data type, order of elements and CPU architecture. Refer to the description of the struct function for more detail.

式やリストのデータが指定されない時、フォーマットや構造体は 0(ゼロ)で満たされます。
When no data expressions or lists are specified, formats or structures are filled with 0s (zeros).

str-format には、次の文字が使えます:
The following characters are used in str-format::

formatdescription
c a signed 8-bit number
b an unsigned 8-bit number
d a signed 16-bit short number
u an unsigned 16-bit short number
ld a signed 32-bit long number
lu an unsigned 32-bit long number
Ld a signed 64-bit long number
Lu an unsigned 64-bit long number
f a float in 32-bit representation
lf a double float in 64-bit representation
sn a string of n null padded ASCII characters
nn n null characters
> switch to big endian byte order
< switch to little endian byte order

浮動小数点を bcdldlu フォーマットで渡された時、pack は全て整数に変換します。 同様に flf で渡された時、整数を浮動小数点に変換します。
pack will convert all floats into integers when passed to b, c, d, ld, or lu formats. It will also convert integers into floats when passing them to f and lf formats.

(pack "c c c" 65 66 67)   "ABC"
(unpack "c c c" "ABC")    (65 66 67)

(pack "c c c" 0 1 2)              "\000\001\002"
(unpack "c c c" "\000\001\002")   (0 1 2)

(set 's (pack "c d u" 10 12345 56789))
(unpack "c d u" s)   (10 12345 56789)

(set 's (pack "s10 f" "result" 1.23))
(unpack "s10 f" s)
 ("result\000\000\000\000" 1.230000019)

(pack "n10")  "\000\000\000\000\000\000\000\000\000\000"

(set 's (pack "s3 lf" "result" 1.23))
(unpack "s3 f" s)   ("res" 1.23)

(set 's (pack "c n7 c" 11 22))
(unpack "c n7 c" s)   (11 22))

(unpack "b" (pack "b" -1.0))   (255)
(unpack "f" (pack "f" 123))    (123)

最後2行では、フォーマット指定で浮動小数点が整数に変換されるのを示しています。
The last two statements show how floating point numbers are converted into integers when required by the format specification.

パックする式はリストで与えることもできます:
The expressions to pack can also be given in a list:

(set 'lst '("A" "B" "C"))
(set 'adr (pack "lululu" lst))
(map get-string (unpack "lululu" adr))     ("A" "B" "C")

pack ではリストが直接参照されます。 そのため、 adr で渡されるポインタが有効になることに注意してください。 adr は C 言語では char * adr[] のように書け、32 ビット文字列ポインタ・アレイへの 32 ビット・ポインタを表します。64 ビット newLISP 版では 64 ビット・ポインタを表します。
Note that the list should be referenced directly in pack, so the pointers passed by adr are valid. adr would be written as char * adr[] in the C-programming language and represents a 32-bit pointer to an array of 32-bit string pointers or a 64-bit pointers on the 64-bit version of newLISP.

>< 指定は、 パック及びアンパック時のバイト順をリトル・エンディアンビッグ・エンディアン に切り替えるために使えます:
The > and < specifiers can be used to switch between little endian and big endian byte order when packing or unpacking:

(pack "d" 1)    "\001\000"  ;; on little endian CPU
(pack ">d" 1)   "\000\001"  ;; force big endian

(pack "ld" 1)    "\001\000\000\000" ;; on little endian CPU
(pack "<ld" 1)   "\000\000\000\001" ;; force big endian

(pack ">u <u" 1 1)  "\000\001\001\000" ;; switch twice

バイト順の切り替えは、16ビット長、32ビット長、64ビット長の数値フォーマットに影響します。
Switching the byte order will affect all number formats with 16-, 32-, or 64-bit sizes.

パックとアンパックのフォーマットが同じである必要はありません:
The pack and unpack format need not be the same:

(set 's (pack "s3" "ABC"))
(unpack "c c c" s)   (65 66 67)

例では、フォーマット指定子間にスペースを入れています。 これは要求されませんが、可読性を良くします。
The examples show spaces between the format specifiers. These are not required but can be used to improve readability.

UTF-8 文字列に packunpack を使うと:
Using pack and unpack on UTF-8 strings:

(set 'txt "我能吞下玻璃而不伤身体。") 
 "我能吞下玻璃而不伤身体。"
(set 'lst (unpack (dup "b" (length txt)) txt)) 
 (230 136 145 232 ... 147 227 128 130)
(pack (dup "b" (length lst)) lst) 
 "我能吞下玻璃而不伤身体。"

関数 addressget-intget-longget-charget-stringunpack も見てください。
See also the address, get-int, get-long, get-char, get-string, and unpack functions.



parse

syntax: (parse str-data [str-break [regex-option]])

str-data の評価結果の文字列を文字列トークンに分解し、リストにして返します。 parsestr-break が無い時、newLISP の内部解析ルールに従ってトークン化します。 特定の一文字列でトークン化するためには、その文字列を str-break に指定します。 regex-option 番号を指定すれば、str-break に正規表現パターンが使えます。
Breaks the string that results from evaluating str-data into string tokens, which are then returned in a list. When no str-break is given, parse tokenizes according to newLISP's internal parsing rules. A string may be specified in str-break for tokenizing only at the occurrence of a string. If an regex-option number is specified, a regular expression pattern may be used in str-break.

str-break が指定されない時、トークンの最大サイズは引用文字列なら2048、識別子なら256です。 この場合、newLISP は newLISP ソース解析時と同じ速さでトークン化します。 str-break が指定された時のトークンの長さには、制限がありません。 文字列 str-data を文字列 str-break で分けるために、違うアルゴリズムが使われるからです。
When str-break is not specified, the maximum token size is 2048 for quoted strings and 256 for identifiers. In this case, newLISP uses the same faster tokenizer it uses for parsing newLISP source. If str-break is specified, there is no limitation on the length of tokens. A different algorithm is used that splits the source string str-data at the string in str-break.

; no break string specified
(parse "hello how are you")      ("hello" "how" "are" "you")

; strings break after spaces, parentheses, commas, colons and numbers. 
; Spaces and the colon are swollowed
(parse "weight is 10lbs")       
(parse "one:two:three" ":")      ("one" "two" "three")

;; specifying a break string
(parse "one--two--three" "--")   ("one" "two" "three")

; a regex option causes regex parsing
(parse "one-two--three---four" "-+" 0) 
 ("one" "two" "three" "four")

(parse "hello regular   expression 1, 2, 3" {,\s*|\s+} 0)
 ("hello" "regular" "expression" "1" "2" "3")

最後の二つの例は、デフォルトのオプション 0(ゼロ)で文字列を分解する正規表現を示しています。 {} (左と右の波括弧) の代わりに、ダブルクォートをパターン境界に使うことができます。 その場合は、パターン内に二重のバックスラッシュ(訳注:日本語環境では円記号 ¥ )を使用する必要があります。 最後のパターンは、CSV(カンマ区切り)ファイルの解析に使えます。 正規表現のオプション番号は regex で見てください。
The last two examples show a regular expression as the break string with the default option 0 (zero). Instead of { and } (left and right curly brackets), double quotes can be used to limit the pattern. In this case, double backslashes must be used inside the pattern. The last pattern could be used for parsing CSV (Comma Separated Values) files. For the regular expression option numbers, see regex.

parse は、 分離子セパレータ周りの空フィールドを空文字列として返します:
parse will return empty fields around separators as empty strings:

; empty fields around separators returned as empty strings
(parse "1,2,3," ",")  ("1" "2" "3" "")
(parse "1,,,4" ",")   ("1" "" "" "4")
(parse "," ",")       ("" "")

(parse "")       ()
(parse "" " ")   ()

空フィールドを持つレコードの解析時に、この振る舞いが必要になります。
This behavior is needed when parsing records with empty fields.

空文字列の解析では、結果は常に空リストになります。
Parsing an empty string will always result in an empty list.

文字列分解用関数 regex や正規表現の使える関数 directoryfindfind-allregexreplacesearch も見てください。
Use the regex function to break strings up and the directory, find, find-all, regex, replace, and search functions for using regular expressions.



peek

syntax: (peek int-handle)

ファイル記述子デスクリプタで読み取り可能なバイト数を返します。 ファイル記述子デスクリプタが無効なら nil を返します。 peekstdin のチェックにも使えます。 この関数は Unix ライク・オペレーティング・システム上でのみ使えます。
Returns the number of bytes ready to be read on a file descriptor; otherwise, it returns nil if the file descriptor is invalid. peek can also be used to check stdin. This function is only available on Unix-like operating systems.

(peek 0)  ; check # of bytes ready on stdin

ネットワーク・ソケットのチェックや利用可能なバイト数には、関数 net-peek を使ってください。 Uinx システムでは、net-peek がファイル記述子デスクリプタのチェックに使えます。 違いは、net-peeknet-error もセットすることです。
Use the net-peek function to check for network sockets, or for the number of available bytes on them. On Unix systems, net-peek can be used to check file descriptors. The difference is that net-peek also sets net-error.



pipe

syntax: (pipe)

内部通信用パイプを作成し、readwrite 用ハンドルをリストにして返します。
Creates an inter-process communications pipe and returns the read and write handles to it within a list.

(pipe)   (3 4)  ; 3 for read, 4 for writing

パイプ・ハンドルは、 process で起動した子プロセスや内部プロセス通信用の fork へ渡されます。
The pipe handles can be passed to a child process launched via process or to fork for inter-process communications.

パイプは、書き込みに関してはブロックしませんが、読み取りの際は読み取り可能になるまでブロックすることに注意してください。 read-line は、改行文字を受け取るまでブロックします。 read は、全プロセスで閉じられた書き込み終了を持っていないパイプで読み取り可能な文字数が指定されたものより少ない時、ブロックします。
Note that the pipe does not block when being written to, but it does block reading until bytes are available. A read-line blocks until a newline character is received. A read blocks when fewer characters than specified are available from a pipe that has not had the writing end closed by all processes.

要求されれば、一個以上のパイプが開かれます。
More than one pipe can be opened if required.

newLISP では 名前付きパイプ も使えます。 詳細は関数 open を見てください。
newLISP can also use named pipes. See the open function for further information.



pmt

syntax: (pmt num-interest num-periods num-principal [num-future-value [int-type]])

固定金利 num-interest と支払回数 num-periods 回で(訳注: num-principal のローンを組む時の)一回あたりのローン支払い額を計算します。 num-future-value は最後のローン額です(普通は 0.0)。 期間の終わりに支払うなら int-type0(ゼロ)にするか省略し、期間の最初に支払うなら int-type を 1 にします。
Calculates the payment for a loan based on a constant interest of num-interest and constant payments over num-periods of time. num-future-value is the value of the loan at the end (typically 0.0). If payment is at the end of the period, int-type is 0 (zero) or int-type is omitted; for payment at the beginning of each period, int-type is 1.

(pmt (div 0.07 12) 240 100000)   -775.2989356

上記例では、年利 7%で $100,000 のローンを組むと毎回の支払額が $775.30 になると計算されます。 20 年の月払いで計算しています(20 * 12 = 240 ヶ月)。 これが示しているのは、借金の典型的な支払い方法の計算です。
The above example calculates a payment of $775.30 for a loan of $100,000 at a yearly interest rate of 7 percent. It is calculated monthly and paid over 20 years (20 * 12 = 240 monthly periods). This illustrates the typical way payment is calculated for mortgages.

関数 fvirrnpernpvpv も見てください。
See also the fv, irr, nper, npv, and pv functions.



pop ! utf8

syntax: (pop list [int-index-1 [int-index-2 ... ]])
syntax: (pop list [list-indexes])

syntax: (pop str [int-index [int-length]])

pop を使うと、リストから要素を、あるいは文字列から文字を取り去ることができます。
Using pop, elements can be removed from lists and characters from strings.

第一構文の pop は、list を評価することで得られたリストから要素を抜き出します。 第二パラメータが存在するなら、int-index の要素を抜き出します。 文字列、リスト、アレイの要素指定 も見てください。
In the first syntax, pop extracts an element from the list found by evaluating list. If a second parameter is present, the element at int-index is extracted and returned. See also Indexing elements of strings and lists.

第二の型では、インデックスをリスト list-indexes で指定します。 この方法により、インデックスのリストを返す refref-all と一緒に pop が簡単に使えます。
In the second version, indices are specified in the list list-indexes. This way, pop works easily together with ref and ref-all, which return lists of indices.

pop は目標リストの内容を変更します。 抜き出された要素が返ります。
pop changes the contents of the target list. The popped element is returned.

(set 'pList '((f g) a b c "hello" d e 10))

(pop pList)   (f g)
(pop pList)   a
pList         (b c "hello" d e 10)

(pop pList 3)     d
(pop pList -1)   10
pList             (b c "hello" e)

(pop pList -1)   e
pList            (b c "hello")

(pop pList -2)   c
pList            (b "hello")

(set 'pList '(a 2 (x y (p q) z)))

(pop pList -1 2 0)   p

;; use indices in a list
(set 'pList '(a b (c d () e)))

(push 'x pList '(2 2 0))  
 (a b (c d (x) e))

pList
 (a b (c d (x) e))

(ref 'x pList)   (2 2 0)

(pop pList '(2 2 0))   x

pop は、一つのインデックスで文字列に使うこともできます(訳注:つまり、インデックス・リストは文字列には使えません):
pop can also be used on strings with one index:

;; use pop on strings

(set 'str "newLISP")

(pop str -4 4)   "LISP"

str   "new"

(pop str 1)   "e"

str   "nw"

(set 'str "x")

(pop str)   "x"
(pop str)   ""

空文字列からの抜き出しは、空文字列を返します。
Popping an empty string will return an empty string.

pop と逆の操作をする関数 push も見てください。
See also the push function, the inverse operation to pop.



pop-assoc !

syntax: (pop-assoc exp-key list-assoc)
syntax: (pop-assoc list-keys list-assoc)

list-assoc の連想リスト から exp-key のキーで参照された連想を抜き出し、抜き出した式を返します。
Removes an association referred to by the key in exp-key from the association list in list-assoc and returns the popped expression.

;; simple associations

(set 'L '((a 1) (b 2) (c 3)))
(pop-assoc 'b L)  (b 2)
L  ((a 1) (c 3))

;; nested associations

(set 'L '((a (b 1) (c (d 2)))))
(pop-assoc 'a L)  (a (b 1) (c (d 2)))
L  ()

(set 'L '((a (b 1) (c (d 2)))))
(pop-assoc '(a b) L)   (b 1)
L   ((a (c (d 2))))

(set 'L '((a (b 1) (c (d 2)))))
(pop-assoc '(a c) L)   (c (d 2))
L  ((a (b 1))))

連想を検索する assoc と連想リストを変更する setf も見てください。
See also assoc for retrieving associations and setf for modifying association lists.



post-url

syntax: (post-url str-url str-content [str-content-type [str-option] [int-timeout [ str-header]]])

str-url の URL に HTTP POST 要求リクエストを送ります。 POST要求リクエスト は、ウェブ入力フォームで収集した情報をウェブ・サイトに投稿するために使われます。 多くの場合、関数 post-url は HTMLフォームで集めた情報をサーバーに送る時のウェブ・ブラウザの振る舞いに似ていますが、ファイルのアップロードにも使えます(HTTPレファレンスを見てください)。 関数はサーバーから戻ってきたページを文字列で返します。
Sends an HTTP POST request to the URL in str-url. POST requests are used to post information collected from web entry forms to a web site. Most of the time, the function post-url mimics what a web browser would do when sending information collected in an HTML form to a server, but it can also be used to upload files (see an HTTP reference). The function returns the page returned from the server in a string.

post-url はエラーに出会うと ERR: で始まるエラーの文字列記述を返します。
When post-url encounters an error, it returns a string description of the error beginning with ERR:.

最後のパラメータ int-timeout は、ミリ秒で指定するタイムアウト値です。 タイムアウトに達する前にホストからの応答レスポンスが受信されないと、文字列 ERR:timeout を返します。
The last parameter, int-timeout, is for an optional timeout value, which is specified in milliseconds. When no response from the host is received before the timeout has expired, the string ERR: timeout is returned.

;; specify content type
(post-url "http://somesite.com/form.pl" 
          "name=johnDoe&city=New%20York" 
          "application/x-www-form-urlencoded")

;; specify content type and timeout
(post-url "http://somesite.com/form.pl" 
          "name=johnDoe&city=New%20York" 
          "application/x-www-form-urlencoded" 8000)

;; assumes default content type and no timeout
(post-url "http://somesite.com/form.pl"
          "name=johnDoe&city=New%20York" 

上記例は、application/x-www-form-urlencoded と呼ばれる指定フォーマットを使って、ユーザ名と都市名をアップロードします。 post-url は、ファイルやバイナリ・データのようなタイプの内容を投稿するためにも使えます。 他の content-type の指定やデータ・エンコード・フォーマットについては、HTTP リファレンスを見てください。 content-type パラメータが省略された時、post-url はデフォルトの型として application/x-www-form-urlencoded を使います。
The above example uploads a user name and city using a special format called application/x-www-form-urlencoded. post-url can be used to post other content types such as files or binary data. See an HTTP reference for other content-type specifications and data encoding formats. When the content-type parameter is omitted, post-url assumes application/x-www-form-urlencoded as the default content type.

Additional parameters(追加のパラメータ)

str-content-type を指定する時は、戻り内容に get-url と同じオプションを取ることができます。 int-timeout オプションを指定するなら、カスタム・ヘッダ・オプション str-header も同様に指定できます。 全オプションの詳細は、関数 get-url を見てください。
When str-content-type is specified, the optional str-option can take the same options as get-url for the returned content. If the int-timeout option is specified, the custom header option str-header can be specified, as well. See the function get-url for details on all options.

関数 get-urlput-url も見てください。
See also the get-url and put-url functions.



pow

syntax: (pow num-1 num-2 [num-3 ... ])
syntax: (pow num-1)

num-1num-2 乗を計算し、続くべき指数のべき乗を計算します。
Calculates num-1 to the power of num-2 and so forth.

(pow 100 2)       10000
(pow 100 0.5)     10
(pow 100 0.5 3)   1000

(pow 3)   9

num-1 のみが引数の時、pow はべき指数を 2 にします。
When num-1 is the only argument, pow assumes 2 for the exponent.



prefix

syntax: (prefix sym)

sym のシンボルのコンテキストを返します:
Returns the context of a symbol in sym:

(setf s 'Foo:bar)       Foo:bar
(prefix s)              Foo
(context? (prefix s))   true

(term s)                          "bar"
(= s (sym (term s) (prefix s)))   true

>(context (prefix s))   ; switches to context Foo
Foo
Foo>

シンボルの名前部分を(訳注:文字列で)取り出す term も見てください。
See also term to extract the term part of a symbol.



pretty-print

syntax: (pretty-print [int-length [str-tab [str-fp-format]])

printsavesource の出力やインターラクティブ・コンソールへの整形出力を再設定します。 最初のパラメータ int-length は行の長さの最大を指定し、str-tab は行のインデントに用いる文字列を指定します。 第三パラメータ str-fp-format は、浮動小数点数出力時のデフォルトのフォーマットを記述します。 全てのパラメータはオプションです。 pretty-print は現行の設定内容を返すか、パラメータが指定された時に新規設定内容を返します。
Reformats expressions for print, save, or source and when printing in an interactive console. The first parameter, int-length, specifies the maximum line length, and str-tab specifies the string used to indent lines. The third parameter str-fp-format describes the default format for printing floating point numbers. All parameters are optional. pretty-print returns the current settings or the new settings when parameters are specified.

(pretty-print)   (80 " " "%1.15g")  ; default setting

(pretty-print 90 "\t")   (90 "\t" "%1.15g")

(pretty-print 100)   (100 "\t" "%1.15g") 

(sin 1)     0.841470984807897
(pretty-print 80 " " "%1.3f")
(sin 1)     0.841

(set 'x 0.0)
x    0.000

最初の例では、デフォルトの設定内容である行の最大文字数 80、space のインデント文字を報告します。 二番目の例では、行の最大 90 とインデント文字に TAB 文字を指定しています。 三番目の例では、行の長さのみを変えています。 最後の例では、浮動小数点数のデフォルトのフォーマットを変更しています。 これは、少数部を持たない浮動小数点数をフォーマット指定せずに出力する時でも、数値を浮動小数点数として認識できようにしておきたい時に役立ちます。 カスタム・フォーマット無しでは、(訳注:上記例の)x は浮動小数点数だとは分からない 0 として出力されます。 フォーマット指定されていない浮動小数点数を出力する全ての状況が影響を受けます。
The first example reports the default settings of 80 for the maximum line length and a space character for indenting. The second example changes the line length to 90 and the indent to a TAB character. The third example changes the line length only. The last example changes the default format for floating point numbers. This is useful when printing unformatted floating point numbers without fractional parts, and these numbers should still be recognizable as floating point numbers. Without the custom format, x would be printed as 0 indistinguishable from floating point number. All situations where unformatted floating point numbers are printed, are affected.

pretty-print は、出力の行の形式が崩れるのを防止するためには使えないことに注意してください。 この整形出力を完全に抑制したい時は、次のように関数 string を使ってください。式が整形されない生の文字列に変換されます:
Note that pretty-print cannot be used to prevent line breaks from being printed. To completely suppress pretty printing, use the function string to convert the expression to a raw unformatted string as follows:

;; print without formatting

(print (string my-expression))	


primitive?

syntax: (primitive? exp)

exp を評価して、組込シンボル(訳注:つまり、組込関数)かどうかをテストし、結果次第で truenil を返します。 全ての組込関数と import で作られた関数も、組込関数として評価されます。
Evaluates and tests if exp is a primitive symbol and returns true or nil depending on the result. All built-in functions and functions created using import are primitives.

(set 'var define)
(primitive? var)   true


print

syntax: (print exp-1 [exp-2 ... ])

exp-1 以下を評価して、カレント I/O デバイスに出力します。 デフォルトはコンソール・ウィンドウです。 異なる I/O デバイスへの指定方法の詳細は、組込関数 device を見てください。
Evaluates and prints exp-1— to the current I/O device, which defaults to the console window. See the built-in function device for details on how to specify a different I/O device.

リスト式は、開いた括弧の入れ子レベルでインデントされます。
List expressions are indented by the nesting levels of their opening parentheses.

いくつかの特殊文字は、エスケープ文字 \(訳注:日本語環境では円記号 ¥ )を使って文字列中に含められます:
Several special characters may be included in strings encoded with the escape character \:

characterdescription
\n ライン・フィード文字 (ASCII 10)
the line-feed character (ASCII 10)
\r キャリッジ・リターン文字 (ASCII 13)
the carriage-return character (ASCII 13)
\t タブ文字 (ASCII 9)
the tab character (ASCII 9)
\nnn 十進数のアスキー・コードで、nnn は 000 から 255 です
where nnn is a decimal ASCII code between 000 and 255
\xnn 十六進数コードで、nn は 00 から FF です
where nn is a hexadecimal ASCII code between 00 and FF


(print (set 'res (+ 1 2 3))) 
(print "the result is" res "\n")

"\065\066\067"   "ABC"

出力の終わりを改行にしたい時は println を使ってください。
To finish printing with a line-feed, use println.



println

syntax: (println exp-1 [exp-2 ... ])

exp-1 以下を評価して、カレント I/O デバイスに出力します。 デフォルトはコンソール・ウィンドウです。 改行が最後に出力されます。 異なる I/O デバイスの指定方法の詳細は、組込関数 device を見てください。 printlnprint と全く同じに作用しますが、最後に改行文字を出します。
Evaluates and prints exp-1— to the current I/O device, which defaults to the console window. A line-feed is printed at the end. See the built-in function device for details on how to specify a different I/O device. println works exactly like print but emits a line-feed character at the end.

関数 write-lineprint も見てください。
See also the write-line and print functions.



prob-chi2

syntax: (prob-chi2 num-chi2 int-df)

帰無仮説下、自由度 num-df 以上で観測されたカイ二乗統計値 num-chi2 の確率(訳注:危険率)を返します(訳注:EXCELの CHIDIST(x,自由度)に相当)。 prob-chi2 は、不完全ガンマ関数 gammai から計算されます(訳注:EXCELの CHIDIST(x, 自由度)に相当)。
Returns the probability of an observed Chi² statistic in num-chi2 with num-df degrees of freedom to be equal or greater under the null hypothesis. prob-chi2 is derived from the incomplete Gamma function gammai.

(prob-chi2 10 6)   0.1246520195

逆関数 crit-chi2 も見てください。
See also the inverse function crit-chi2.



prob-f

syntax: (prob-f num-f int-df1 int-df2)

帰無仮説下、自由度 int-df1int-df2 以上で観測された F 統計値 num-f の確率(訳注:危険率)を返します(訳注:EXCELの FDIST(x, 自由度1, 自由度2)に相当)。
Returns the probability of an observed F statistic in num-f with int-df1 and int-df2 degrees of freedom to be equal or greater under the null hypothesis.

(prob-f 2.75 10 12)   0.0501990804

逆関数 crit-f も見てください。
See also the inverse function crit-f.



prob-t

syntax: (prob-t num-t int-df1)

帰無仮説下、自由度 int-df1 以上で観測された スチューデントの t 統計値 num-t の確率(訳注:危険率)を返します(訳注:EXCELの TDIST(x,自由度,1)に相当)。
Returns the probability of an observed Student's t statistic in num-t with int-df degrees of freedom to be equal or greater under the null hypothesis.

(prob-t 1.76 14)   0.05011454551

逆関数 crit-t も見てください。
See also the inverse function crit-t.



prob-z

syntax: (prob-z num-z)

平均値 0.0、標準偏差 1.0 の正規分布において、観測値 num-z を超えない確率を返します(訳注:EXCELのNORMSDIST(z)に相当)。
Returns the probability of num-z, not to exceed the observed value where num-z is a normal distributed value with a mean of 0.0 and a standard deviation of 1.0.

(prob-z 0.0)   0.5

逆関数 crit-z も見てください。
See also the inverse function crit-z.



process

syntax: (process str-command)
syntax: (process str-command int-pipe-in int-pipe-out [int-win-option])
syntax: (process str-command int-pipe-in int-pipe-out [int-unix-pipe-error])

第一構文の process は、str-command で指定されたプロセスを起動し、直ちにプロセスID かプロセス生成できなかった時の nil を返します。 このプロセスは指定されたプログラムを実行しますが、str-command が実行できなかった時は直ちに無くなります。
In the first syntax, process launches a process specified in str-command and immediately returns with a process ID or nil if a process could not be created. This process will execute the program specified or immediately die if str-command could not be executed.

macOS や他の Linux では、アプリケーションやスクリプトは、フル・パス名で指定されなければなりません。 新プロセスは、OS の環境を親プロセスから受け継ぎます。
On macOS and other Unixes, the application or script must be specified with its full path-name. The new process inherits the OS environment from the parent process.

コマンド・ラインの引数はスペースで分けられます。 スペースを含む引数は、macOS や他の Linux ではシングル・クォートを使って囲みます。 MS Windowsではダブル・クォートを使います。 プロセスがそれ自身で終わらない場合、戻り値のプロセス ID を destroy に使って、走っているプロセスを破棄できます。
Command line arguments are parsed out at spaces. Arguments containing spaces must be delimited using single quotes on macOS and other Unixes. On MS Windows, double quotes are used. The process id returned can be used to destroy the running process using destroy, if the process does not exit by itself.

(process "c:/WINDOWS/system32/notepad.exe")   1894 ; Windows
; or when in executable path
(process "notepad.exe")                       1894 ; Windows


; find out the path of the program to start using exec, 
; if the path is not known

(process (first (exec "which xclock")))   22607 ; on Unix

実行可能なパスが不明な時、Unix なら execwhich コマンドを使ってプログラムを開始できます。 戻り値のプロセス ID はプロセスの destroy に使えます。
If the path of the executable is unknown, exec together with the Unix which command can be used to start a program. The pid returned can be used to destroy the process.

第二構文では、生成されたプロセスの標準入出力がパイプ・ハンドルにリダイレクトされます。 起動したアプリケーションの標準 I/O をパイプに再配置した時は、write-lineread-line または write-bufferread-buffer を通して他のアプリケーションとの通信が可能になります:
In the second syntax, standard input and output of the created process can be redirected to pipe handles. When remapping standard I/O of the launched application to a pipe, it is possible to communicate with the other application via write-line and read-line or write and read statements:

;; Linux/Unix
;; create pipes
(map set '(myin bcout) (pipe))
(map set '(bcin myout) (pipe))   

;; launch Unix 'bc' calculator application
(process "/usr/bin/bc" bcin bcout)  7916

(write-line myout "3 + 4")  ; bc expects a line-feed

(read-line myin)   "7"


;; bc can use bignums with arbitrary precision

(write-line myout "123456789012345 * 123456789012345\n")

(read-line myin)   "15241578753238669120562399025"

;; destroy the process
(destroy 7916)

;; MS Windows
(map set '(myin cmdout) (pipe))
(map set '(cmdin myout) (pipe))

(process "c:/Program Files/newlisp/newlisp.exe -c" cmdin cmdout)
 1284

(write-line myout "(+ 3 4)")

(read-line myin)  "7"

;; destroy the process
(destroy 1284)

MS Windows 版 newLISP では、int-win-option の第四オプション・パラメータにアプリケーションの表示状態制御を指定できます。 このオプションのデフォルトは 1 で、アプリケーション・ウィンドウを表示します。 他に、非表示用の 0 とランチ・バーに最小化する 2 があります。
On MS Windows versions of newLISP, a fourth optional parameter of int-win-option can be specified to control the display status of the application. This option defaults to 1 for showing the application's window, 0 for hiding it, and 2 for showing it minimized on the Windows launch bar.

MS Windows と Linux/Unix の両システムで、標準エラーはデフォルトで標準出力にリダイレクトされます。 Linux/Unix では、標準エラー出力としてオプションのパイプ・ハンドルが int-unix-pipe-error に定義されます。
On both MS Windows and Linux/Unix systems, standard error will be redirected to standard out by default. On Linux/Unix, an optional pipe handle for standard error output can be defined in int-unix-pipe-error.

関数 peek はパイプ・ハンドル上の情報のチェックに使えます:
The function peek can be used to check for information on the pipe handles:

;; create pipes
(map set '(myin bcout) (pipe))
(map set '(bcin myout) (pipe))   
(map set '(errin errout) (pipe))   

;; launch Unix 'bc' calculator application
(process "bc" bcin bcout errout)

(write myout command)

;; wait for bc sending result or error info
(while (and (= (peek myin) 0)
            (= (peek errin) 0)) (sleep 10))

(if (> (peek errin) 0)
	(println (read-line errin)))
	
(if (> (peek myin) 0)
	(println (read-line myin)))

全てのインターラクティブ・コンソール・アプリケーションが、標準 I/O チャンネルに再配置できるわけではありません。 一つのチャンネルのみが inout に再配置されることがあります。 この場合、使用しないチャンネルには 0(ゼロ)を指定してください。 次の宣言文は、起動したアプリケーションの出力のみを使っています:
Not all interactive console applications can have their standard I/O channels remapped. Sometimes only one channel, in or out, can be remapped. In this case, specify 0 (zero) for the unused channel. The following statement uses only the launched application's output:

(process "app" 0 appout)

通常は二つのパイプが使われ、一つが子プロセスへの通信用で、もう一つが子プロセスからの通信用です。
Normally, two pipes are used: one for communications to the child process and the other one for communications from the child process.

内部プロセス通信用関数 pipeshare 及び複数のプロセス間同期用関数 semaphore も見てください。 newLISP プロセスを開始する別の方法である関数 forkspawn を見てください。 両方とも macOS、Linux や Unix ライク・オペレーティング・システムでのみ利用できます。
See also the pipe and share functions for inter-process communications and the semaphore function for synchronization of several processes. See the fork and spawn functions for other ways of starting newLISP processes. Both are only available on macOS, Linux and other Unix like operating systems.



prompt-event

syntax: (prompt-event sym-event-handler | func-event-handler)
syntax: (prompt-event nil)

インターラクティブな newLISP シェルを改良します。 sym-event-handler または func-event-handler は、ユーザ定義関数のシンボルかラムダ関数のどちらかです:
Refines the prompt as shown in the interactive newLISP shell. The sym-event-handler or func-event-handler is either a symbol of a user-defined function or a lambda expression:

prompt-event を元の状態にリセットするには、第二構文を使ってください。
To reset prompt-event to the original state, use the second syntax.

> (prompt-event (fn (ctx) (string ctx ":" (real-path) "$ ")))
$prompt-event
MAIN:/Users/newlisp$ (+ 3 4)
7
MAIN:/Users/newlisp$

prompt-event コードが呼ばれる時の現コンテキストが、関数のパラメータとして渡されまています。 コンピュータの出力は太文字で示されています。
The current context before calling the prompt-event code is passed as a parameter to the function. Computer output is shown in bold.

この例は、現コンテキストに続く > プロンプトがドル・シンボルとディレクトリ名に続くコロン : になっています。 フル・カスタムなシェル、または、カスタム・コマンド・インターラプタを作成するために、この関数と command-event を一緒に使うことができます。
The example redefines the > prompt to be the current context followed by a colon :, followed by the directory name, followed by the dollar symbol. Together with the command-event function this can be used to create fully customized shells or custom command interpreters.

prompt-event の関数は、最大63文字の文字列を返さなくてはなりません。 文字列が返らなければ、プロンプトが変化しないからです。
The function in prompt-event must return a string of 63 characters maximum. Not returning a string will leave the prompt unchanged.



protected?

syntax: (protected? sym)

シンボル sym がプロテクトされているかどうかをチェックします。 プロテクトされているシンボルは、組込関数、コンテキスト・シンボル、関数 constant を使って constant にされた全てのシンボルです:
Checks if a symbol in sym is protected. Protected symbols are built-in functions, context symbols, and all symbols made constant using the constant function:

(protected? 'println)     true
(constant 'aVar 123)
(protected? 'aVar)        true


push ! utf8

syntax: (push exp list [int-index-1 [int-index-2 ... ]])
syntax: (push exp list [list-indexes])

syntax: (push str-1 str-2 [int-index])

exp の値をリスト list に挿入します。 int-index がある時、要素はインデックスの位置に挿入されます。 インデックスがない時は、インデックスが 0(ゼロ)である最初の要素として挿入されます。 push は、目標リストの内容を変更する破壊的関数です。
Inserts the value of exp into the list list. If int-index is present, the element is inserted at that index. If the index is absent, the element is inserted at index 0 (zero), the first element. push is a destructive operation that changes the contents of the target list.

変更されたリストが返され、他の組込関数で参照動作可能です。 文字列、リスト、アレイの要素指定 も見てください。
The list changed is returned as a reference on which other built-in functions can work. See also Indexing elements of strings and lists.

一個より多い int-index がある時、インデックスは入れ子構造のリストのアクセスとして使われます。 (リスト要素に一致しない)不適切なインデックス(訳注:入れ子構造と合っていないインデックス)は、破棄されます。(訳注:不適切なインデックスが破棄されるだけで、破棄されない部分のインデックスが有効であれば、要素はその位置に挿入されます。)
If more than one int-index is present, the indices are used to access a nested list structure. Improper indices (those not matching list elements) are discarded.

第二の型は list-indexes のリストを取りますが、他は第一の型と同じです。 この方法なら、インデックスのリストを返す refref-all と一緒に push を簡単使えます。
The second version takes a list of list-indexes but is otherwise identical to the first. In this way, push works easily together with ref and ref-all, which return lists of indices.

list にリストが入っていないなら、listnil であるべきです。その際は、空リストに初期化されます。
If list does not contain a list, list must contain a nil and will be initialized to the empty list.

int-index-1 を使ってリストの最後に繰り返し push するように最適化されていて、インデックス無しでリストの最初への push することより高速です。 この動作は、効率良くリストを増やすために有効です。
Repeatedly using push to the end of a list using -1 as the int-index is optimized and as fast as pushing to the front of a list with no index at all. This can be used to efficiently grow a list.

; inserting in front
(set 'pList '(b c))   (b c)
(push 'a pList)       (a b c)
pList                 (a b c)

; insert at index
(push "hello" pList 2)   (a b "hello" c)

; optimized appending at the end
(push 'z pList -1)   (a b "hello" c z)

; inserting lists in lists
(push '(f g) pList)   ((f g) a b "hello" c z)

; inserting at negative index
(push 'x pList -3)   ((f g) a b "hello" x c z)

; using multiple indices
(push 'h pList 0 -1)   ((f g h) a b "hello" x c z)

; use indices in a list
(set 'pList '(a b (c d () e)))

(push 'x pList '(2 2 0))   (a b (c d (x) e))

(ref 'x pList)    (2 2 0)

(pop pList '(2 2 0))   x

; the target list is a place reference
(set 'lst '((a 1) (b 2) (c 3) (d)))

(push 4 (assoc 'd lst) -1)  (d 4)

lst  ((a 1) (b 2) (c 3) (d 4))


; push on un-initialized symbol
aVar   nil 

(push 999 aVar)   (999)

aVar   (999)

pushpop を組み合わせて、キューを作ることができます:
push and pop can be combined to model a queue:

; pop and push a as a queue
(set 'Q '(a b c d e))

(pop (push 'f Q -1))  a
(pop (push 'g Q -1))  b

Q   (c d e f g)

push は変更したリストへの参照を返すので、それ(訳注:返された参照)を pop で直接扱えます。
Because push returns a reference to the modified list, pop can work on it directly.

第三構文の push は文字列の変更に使えます。 int-index の使用は、バイト位置ではなく文字位置で参照します。 UTF-8 文字は多バイト文字かもしれません。
In the third syntax push can be used to change strings. When int-index is used, it refers to character positions rather than byte positions. UTF-8 characters may be multi-byte characters.

;; push on strings

(set 'str "abcdefg")

(push "hijk" str -1)   "abcdefghijk"
str                    "abcdefghijk"

(push "123" str)   "123abcdefghijk"
(push "4" str 3)   "1234abcdefghijk"

(set 'str "\u03b1\u03b2\u03b3")    "ホアホイホウ"

(push "*" str 1)    "ホア*ホイホウ"

;; push on a string reference

(set 'lst '("abc" "xyz"))

(push x (lst 0))  "xabc"

lst  ("xabc" "xyz")

push と逆操作の関数 pop も見てください。
See also the pop function, which is the inverse operation to push.



put-url

syntax: (put-url str-url str-content [str-option] [int-timeout [str-header]])

HTTP PUT プロトコルは、str-url で指定されたファイルへ str-content の情報を転送するために使われます。 あまり知られていない HTTP PUT モードは、HTML エディタからウェブ・サーバーへウェブ・ページを転送するために頻繁に使われます。 PUT モードを使うためには、ウェブ・サーバーのソフトウェアが正しく設定されている必要があります。 Apache ウェブ・サーバーでは、ディレクトリ・アクセス権が設定されているセクションに 'Script PUT' 命令を使います。
The HTTP PUT protocol is used to transfer information in str-content to a file specified in str-url. The lesser-known HTTP PUT mode is frequently used for transferring web pages from HTML editors to Web servers. In order to use PUT mode, the web server's software must be configured correctly. On the Apache web server, use the 'Script PUT' directive in the section where directory access rights are configured.

str-urlfile:// で始まっているならば、str-content はローカル・ファイル・システムに書き込まれます。
If str-url starts with file:// then str-content is written to the local file system.

オプションで、最後のパラメータに int-timeout 値をミリ秒単位で指定できます。 ホストが応答レスポンスを返さないか、タイムアウトに達した時、put-urlERR: timeout を返します。 他のエラー条件では、put-urlERR: で始まる文字列とエラーの記述を返します。
Optionally, an int-timeout value can be specified in milliseconds as the last parameter. put-url will return ERR: timeout when the host gives no response and the timeout expires. On other error conditions, put-url returns a string starting with ERR: and the description of the error.

put-url 要求リクエストは、newLISP サーバー・ノードでも解釈されますが、-http-safe モードで始まっている時は実行されません。
put-url requests are also understood by newLISP server nodes, but will not be served when the server is started in -http-safe mode.

(put-url "http://asite.com/myFile.txt" "Hi there")
(put-url "http://asite.com/myFile.txt" "Hi there" 2000)

(put-url "http://asite.com/webpage.html" 
    (read-file "webpage.html"))

; write /home/joe/newfile.txt on the local file system
(puts-url "file:///home/joe/newfile.txt" "Hello World!")

最初の例は、ターゲット・サーバー上に myFile.txt で呼ばれるファイルを生成し、それにテキスト文字列 'Hi there' を保存します。 二番目の例は、ローカル・ファイル webpage.htmlasite.com に転送します。
The first example creates a file called myFile.txt on the target server and stores the text string 'Hi there' in it. In the second example, the local file webpage.html is transferred to asite.com.

Apache ウェブ・サーバーでは、次のように httpd.conf に設定することができます:
On an Apache web server, the following could be configured in httpd.conf.

<directory /www/htdocs>
Options All
Script PUT /cgi-bin/put.cgi
</directory>

スクリプト put.cgi は、STDIN を通してウェブ・サーバーからの内容を受信するためのコードを含んでいます。 次は、Apache ウェブ・サーバー用に newLISP で書かれた put.cgi の動作です:
The script put.cgi would contain code to receive content from the web server via STDIN. The following is a working put.cgi written in newLISP for the Apache web server:

#!/usr/home/johndoe/bin/newlisp
#
#
# get PUT method data from CGI STDIN 
# and write data to a file specified
# int the PUT request
# 
#


(print "Content-Type: text/html\n\n")

(set 'cnt 0)
(set 'result "")

(if (= "PUT" (env "REQUEST_METHOD"))
    (begin
      (set 'len (int (env "CONTENT_LENGTH")))

      (while (< cnt len)
          (set 'n (read (device) buffer len))
          (if (not n) 
            (set 'cnt len) 
            (begin 
              (inc cnt n)
              (write result buffer))))
              
      (set 'path (append 
              "/usr/home/johndoe" 
              (env "PATH_TRANSLATED")))

      (write-file path result)
    )
)

(exit)

アップロードされた悪意のあるスクリプトのCGI実行を避けるために、スクリプトが ".txt" を付加することに注意してください。 フル・パスを構成する二行がウェブ・サーバー環境によっては、異なる動作をするかもしれないことにも注意してください。 ウェブ・サーバーで正しいファイル・パスを構成するために、環境変数をチェックしてください。
Note that the script appends ".txt" to the path to avoid the CGI execution of uploaded malicious scripts. Note also that the two lines where the file path is composed may work differently in your web server environment. Check environment variables passed by your web server for composition of the right file path.

put-urlput.cgi によって返される内容を返します。
put-url returns content returned by the put.cgi script.

Additional parameters(追加のパラメータ)

str-option には、戻り内容に get-url と同じオプションを取ることができます。 int-timeout オプションを指定するなら、カスタム・ヘッダ・オプション str-header も同様に指定できます。 全オプションの詳細は、関数 get-url を見てください。
In str-option can take the same options as get-url for the returned content. If the int-timeout option is specified, the custom header option str-header can be specified, as well. See the function get-url for details on all options.

関数 get-urlmultipart/form-data 形式データを整形する時のファイルのアップロードに使われる post-url も見てください。
See also the functions get-url and post-url, which can be used to upload files when formatting form data as multipart/form-data.



pv

syntax: (pv num-int num-nper num-pmt [num-fv [int-type]])

固定金利num-interest と 固定支払額 num-pmt で支払回数 num-nper の場合のローン残高を計算します。 最終ローン残高 num-fv は省略されると 0.0 になります。 期間の終わりに支払うなら int-type0(ゼロ)か int-type は 省略され、期間の最初に支払うなら int-type は 1 です。
Calculates the present value of a loan with the constant interest rate num-interest and the constant payment num-pmt after num-nper number of payments. The future value num-fv is assumed to be 0.0 if omitted. If payment is at the end of the period, int-type is 0 (zero) or int-type is omitted; for payment at the beginning of each period, int-type is 1.

(pv (div 0.07 12) 240 775.30)   -100000.1373

この例では、(future value が 0.0 で) 年利7%で240ヶ月、毎月775.30 ドル支払うローンの金額が $100,000.14 となります。
In the example, a loan that would be paid off (future value = 0.0) in 240 payments of $775.30 at a constant interest rate of 7 percent per year would start out at $100,000.14.

関数 fvirrnpernpvpmt も見てください。
See also the fv, irr, nper, npv, and pmt functions.



quote

syntax: (quote exp)

exp を評価せずに返します。 exp への '(シングル・クォート)先付けと同じ効果が得られます。 実行時に関数 quote はなくなり、先付けの ' クォートはコード変換中に保護エンベロープ(クォート・セル)に変換されます。
Returns exp without evaluating it. The same effect can be obtained by prepending a ' (single quote) to exp. The function quote is resolved during runtime, the prepended ' quote is translated into a protective envelope (quote cell) during code translation.

(quote x)          x
(quote 123)        123
(quote (a b c))    (a b c)
(= (quote x) 'x)   true


quote?

syntax: (quote? exp)

exp を評価し、クォートされているかどうかをテストします。 結果次第で、truenil が返ります。
Evaluates and tests whether exp is quoted. Returns true or nil depending on the result.

(set 'var ''x)   'x
(quote? var)     true

(訳注:例の) set 宣言文では、 ''x が 2回クォートされることに注意してください。 それは、最初のクォートが set の引数としての評価で無くなるからです。
Note that in the set statement, ''x is quoted twice because the first quote is lost during the evaluation of the set assignment.



rand

syntax: (rand int-range [int-N])

int-range の式を評価して、0 ~ (int-range - 1) 間の範囲で乱数を一つ生成します。 0 (zero) が渡されると、内部乱数発生器に C 関数 time() による現在値を使って初期化を行います。 オプションで、int-N 個の長さの乱数リストを返す第二パラメータを指定できます。
Evaluates the expression in int-range and generates a random number in the range of 0 (zero) to (int-range - 1). When 0 (zero) is passed, the internal random generator is initialized using the current value returned by the C time() function. Optionally, a second parameter can be specified to return a list of length int-N of random numbers.

(dotimes (x 100) (print (rand 2))) =>
11100000110100111100111101 ... 10111101011101111101001100001000

(rand 3 100)   (2 0 1 1 2 0 …)

例の一行目は均等に分配された 01 を出力し、二行目は均等に分配された 012 の 100 個の整数リストを生成します。 浮動小数点数の乱数生成には、関数 randomnormal を使ってください。 その際、乱数発生器の初期化用シード変更には seed を使ってください。
The first line in the example prints equally distributed 0's and 1's, while the second line produces a list of 100 integers with 0, 1, and 2 equally distributed. Use the random and normal functions to generate floating point random numbers, and use seed to vary the initial seed for random number generation.



random

syntax: (random float-offset float-scale int-n)
syntax: (random float-offset float-scale)

第一形式の random は、float-offset のオフセットを持ち float-scale の大きさに均等に配される int-n 個の浮動小数点数のリストを返します。 内部乱数生成器の開始点は、seed を使って指定できます。
In the first form, random returns a list of int-n evenly distributed floating point numbers scaled (multiplied) by float-scale, with an added offset of float-offset. The starting point of the internal random generator can be seeded using seed.

(random 0 1 10)
 (0.10898973 0.69823783 0.56434872 0.041507289 0.16516733
    0.81540917 0.68553784 0.76471068 0.82314585 0.95924564)

第二形式を使うと、random は均等に配された数値を一つ返します:
When used in the second form, random returns a single evenly distributed number:

(random 10 5)   11.0971

パラメータなしの時、random は平均を 0.0、標準偏差を 1.0 と見なします。
When no parameters are given, random assumes a mean of 0.0 and a standard deviation of 1.0.

関数normalrand も見てください。
See also the normal and rand functions.



randomize

syntax: (randomize list [bool])

list の要素順をランダムに再配列します。
Rearranges the order of elements in list into a random order.

(randomize '(a b c d e f g))   (b a c g d e f)
(randomize (sequence 1 5))     (3 5 4 1 2)

randomize はオプションの bool フラグ無しで、常に前と異なる順序を返します。 このためは、関数には要素の再配置計算が数回必要になるかも知れません。 従って、同じ長さのリスト上でも別々に起動された関数では、実行時間が異なる可能性があります。 入力と同じ出力が許されるなら、nil 以外か true に評価される式を bool に指定します。(訳注:bool が指定されていなければ引数と同じ順序は返されず、 nil 以外なら同じ順序のリストが返される場合があるということ。)
randomize will always return a sequence different from the previous one without the optional bool flag. This may require the function to calculate several sets of reordered elements, which in turn may lead to different processing times with different invocations of the function on the same input list length. To allow for the output to be equal to the input, true or any expression evaluating to not nil must be specified in bool.

randomize が使っている内部擬似ランダム数列 発生器は、newLISP 開始の度に毎回同じ数列結果を返します。 この数列を変更するためには、関数 seed を使ってください。
randomize uses an internal pseudo random sequence generator that returns the same series of results each time newLISP is started. Use the seed function to change this sequence.



read !

syntax: (read int-file sym-buffer int-size [str-wait])

int-file で指定されたファイルから、バッファ sym-buffer に最大 int-size バイト読み取ります。 読み取りに先立ち、sym-buffer で参照されるデータは如何なるものも消去されます。 int-file のハンドルは、先行する open 宣言文から得られます。 読み取り処理後、シンボル sym-buffer は文字列型のデータを持ちます。 ユーザ定義関数へ入出力を受け渡すコンテキスト・シンボル指定のデフォルト・ファンクタを sym-buffer にすることも可能です。
Reads a maximum of int-size bytes from a file specified in int-file into a buffer in sym-buffer. Any data referenced by the symbol sym-buffer prior to the reading is deleted. The handle in int-file is obtained from a previous open statement. The symbol sym-buffer contains data of type string after the read operation. sym-buffer can also be a default functor specified by a context symbol for reference passing in and out of user-defined functions.

readread-buffer の省略形です。 長い名前の read-buffer は今でも動作しますが、推奨されません、 新しいコードでは避けてください。

read is a shorter writing of read-buffer. The longer form still works but is deprecated and should be avoided in new code.

オプションで、待機文字列を str-wait に指定できます。 read は、int-size で指定された最大バイト数を読み取るか、データ中に str-wait を見つけた時に戻ります。 待機文字列は戻りデータに含まれますが、バイナリ 0(ゼロ)を含んではいけません。
Optionally, a string to be waited for can be specified in str-wait. read will read a maximum amount of bytes specified in int-size or return earlier if str-wait was found in the data. The wait-string is part of the returned data and must not contain binary 0 (zero) characters.

読み取ったバイト数か、待機文字が見つからなかった時の nil を返します。 如何なる場合も、読み取られたバイトは sym-buffer で指定されるバッファに置かれ、読み取られたファイルのファイル・ポインタは前に進みます。 読み取られなかった時、sym-buffer の中身は nil になります。
Returns the number of bytes read or nil when the wait-string was not found. In any case, the bytes read are put into the buffer pointed to by sym-buffer, and the file pointer of the file read is moved forward. If no new bytes have been read, sym-buffer will contain nil.

(set 'handle (open "aFile.ext" "read"))
(read handle buff 200)

ファイル aFile.ext からシンボル buff に 200 バイト読み込まれます。
Reads 200 bytes into the symbol buff from the file aFile.ext.

(read handle buff 1000 "password:")

1000バイトか、文字列 password: に出会うまで読み取られます。 文字列 password: は、返されるデータの一部です。
Reads 1000 bytes or until the string password: is encountered. The string password: will be part of the data returned.

関数 write も見てください。 ファイルの特定位置から読み出すには関数 seek を使います。
See also the write function. To start reading at a specific position in the file, use the seek function.



read-char

syntax: (read-char [int-file])

int-file のファイル・ハンドルで指定されたファイルから 1 バイト読み取ります。 ファイル・ハンドルを指定しなければ、現行の I/O デバイス、例えば stdin から読み取ります。 ファイル・ハンドルは先行する open 操作で得られます。 各 read-char は、読み取り毎にファイル・ポインタを一個ずつ進めます。 ファイルの終わりに達したら、nil を返します。
Reads a byte from a file specified by the file handle in int-file or from the current I/O device - e.g. stdin - when no file handle is specified. The file handle is obtained from a previous open operation. Each read-char advances the file pointer by one byte. Once the end of the file is reached, nil is returned.

(define (slow-file-copy from-file to-file)
    (set 'in-file (open from-file "read"))
    (set 'out-file (open to-file "write"))
    (while (set 'chr (read-char in-file))
        (write-char out-file chr))
    (close in-file)
    (close out-file)
    "finished")

一度に行単位で読み取りたい時は、read-linedevice を使ってください。 ファイル・コピー用には、newLISP が copy-file で呼び出される高速な組込関数を提供していることをお忘れなく。 (訳注:ですから、上記例のスクリプトを使う必要は、まず有りません。)
Use read-line and device to read whole text lines at a time. Note that newLISP supplies a fast built-in function called copy-file for copying files.

関数 write-char も見てください。
See also the write-char function.



read-expr

syntax: (read-expr str-source [sym-context [exp-error [int-offset]]])

read-expr は、str-source 中に見つけた最初の式を分析し、翻訳した式を評価せずに返します。 のオプションのコンテキスト sym-context が、翻訳された式の名前空間を指定します。
read-expr parses the first expressions it finds in str-source and returns the translated expression without evaluating it. An optional context in sym-context specifies a namespace for the translated expression.

read-expr が呼ばれた後、システム変数 $count には走査した文字数が入ります。
After a call to read-expr the system variable $count contains the number of characters scanned.

str-source を翻訳中にエラーが起こった場合、exp-error の式が評価され、その結果が返ります。
If an error occurs when translating str-source the expression in exp-error is evaluated and the result returned.

int-offsetstr-source 中で実行を開始するオプセットを指定します。 read-expr が繰り返し呼び出す時、この数値に処理した文字数の $count を使って更新できます。
int-offset specifies an optional offset into str-source where processing should start. When calling read-expr repeatedly this number can be updated using $count, the number of characters processed.

(set 'code "; a statement\n(define (double x) (+ x x))")

(read-expr code)  (define (double x) (+ x x))

$count  41

read-expreval-string のように振る舞いますが、評価のステップがありません:
read-expr behaves similar to eval-string but without the evaluation step:

(read-expr "(+ 3 4)")     (+ 3 4)

(eval-string "(+ 3 4)")   7

read-expr を使えば、評価前に式をプリプロセッシングするカスタム・コード・リーダーをプログラムできます。
Using read-expr a customized code reader can be programmed preprocessing expressions before evaluation.

イベント駆動された式を処理する reader-event も見てください。
See also reader-event for preprocessing expressions event-driven.



read-file

syntax: (read-file str-file-name)

str-file-name のファイルを一気に読み取り、そのデータを文字列バッファで返します。
Reads a file in str-file-name in one swoop and returns a string buffer containing the data.

失敗した時、関数は nil を返します。 ファイルに対して使った時のエラー情報には sys-error を使います。 URL の場合は net-error が詳細なエラー情報を与えます。
On failure the function returns nil. For error information, use sys-error when used on files. When used on URLs net-error gives more error information.

(write-file "myfile.enc" 
    (encrypt (read-file "/home/lisp/myFile") "secret"))

読み取られたファイル myFile は、パスワード "secret" を使って暗号化され、現行のディレクトリ下で "myfile.enc" という名の新ファイルに書き込まれます。
The file myfile is read, then encrypted using the password "secret" before being written back into a new file titled "myfile.enc" in the current directory.

read-file は、str-file-namehttp://file:// 等の URL を取ることができます。 先頭が http:// の時、read-fileget-url と全く同じ動作をするので、(訳注:get-url と)同じ付加パラメータを取ることができます。
read-file can take an http:// or file:// URL in str-file-name. When the prefix is http://, read-file works exactly like get-url and can take the same additional parameters.

(read-file "http://asite.com/somefile.tgz" 10000)

ファイルsomefile.tgz が、リモート位置にある http://asite.com から取り出されます。。 ファイル転送が10秒超えても終わないと、タイム・アウトになります。 このモードの read-file は、リモートにある newLISP サーバーからのファイル転送にも使われます。
The file somefile.tgz is retrieved from the remote location http://asite.com. The file transfer will time out after 10 seconds if it is not finished. In this mode, read-file can also be used to transfer files from remote newLISP server nodes.

関数 write-fileappend-file も見てください。
See also the write-file and append-file functions.



read-key

syntax: (read-key [true])

キーボードからキーを読み取り、整数値を返します。 プラットフォーム OS によっては、ナビーゲーション・キーのために一回より多い read-key の呼び出しが必要になります。 ASCII文字を表すキーは全ての OS で同じ値が返りますが、ナビゲーション・キーやファンクション・キーのようなコントール・シーケンスの場合、戻り値は OS の違いや設定で変わります。
Reads a key from the keyboard and returns an integer value. For navigation keys, more than one read-key call must be made depending of the platform OS. For keys representing ASCII characters, the return value is the same on all OSes, except for navigation keys and other control sequences like function keys, in which case the return values may vary on different OSes and configurations.

true フラグを使うと read-key はノン・ブロッキングになり、キーが押されていなければ(ゼロ)を返します。 この拡張フラグを使わない時、read-key の呼び出しはキーが押されるまでブロッキング状態です。
When using the true flag the read-key is non-blocking and a 0 (zero) is returned when no key has been pressed. When not using the extra flag, the call to read-key is blocking until a key is pressed.

(read-key)   97  ; after hitting the A key
(read-key)   65  ; after hitting the shifted A key
(read-key)   10  ; after hitting [enter] on Linux
(read-key)   13  ; after hitting [enter] on Windows

(read-key true)   0 ; when no key has been pressed

(while (!= (set 'c (read-key)) 1) (println c))

最後の例は、ナビゲーション・キーやファンクション・キーからの戻り値列を確認するために使えます。 ループから抜け出す時は、Ctrl-A を押してください。
The last example can be used to check return sequences from navigation and function keys. To break out of the loop, press Ctrl-A.

newLISP が Unix シェル か MS Windows コマンド・シェル上で走っている時のみに、read-key は動作することに注意してください。 また、newLISP Unix 共有ライブラリ や newLISP MS Windows DLL(ダイナミック・リンク・ライブラリ)上でも動作しません。 これらのライブラリが標準入力を見ていないからです。
Note that read-key will only work when newLISP is running in a Unix shell or Windows command shell. It will also not work when executed by newLISP Unix shared library or newLISP MS Windows DLL (Dynamic Link Library). These libraries are not listening to STD input.



read-line

syntax: (read-line [int-file])

現在の I/O デバイスから改行文字 (ASCII 10) で区切られた文字列を読み取ります。 読み取られる文字列の長さに制限はありません。 改行文字は戻り文字列に含まれません。 行は改行で分割され、改行自体は消えます。 行が復帰 (ASCII 13) で分割されるのは、その後に改行が続いている場合にのみで、どちらの文字も消えます。 復帰がストリームの最後の文字である場合は復帰のみでも分割され、消えます。
Reads from the current I/O device a string delimited by a line-feed character (ASCII 10). There is no limit to the length of the string that can be read. The line-feed character is not part of the returned string. The line always breaks on a line-feed, which is then swallowed. A line breaks on a carriage return (ASCII 13) only if followed by a line-feed, in which case both characters are discarded. A carriage return alone only breaks and is swallowed if it is the last character in the stream.

デフォルトで、現行 device はキーボード (device 0) です。 異なる I/O デバイス(例えば、ファイルとか)を指定するためには、組込関数 device を使ってください。 オプションで、先行する open 宣言文で得られるファイル・ハンドルを int-file に指定できます。
By default, the current device is the keyboard (device 0). Use the built-in function device to specify a different I/O device (e.g., a file). Optionally, a file handle can be specified in the int-file obtained from a previous open statement.

read-line 操作の最新のバッファ内容は、current-line を使って取り出せます。
The last buffer contents from a read-line operation can be retrieved using current-line.

CGI プログラムやパイプ上で、read-line がファイルや stdin から読み取っている時、入力が終わった時点で nil を返します。
When read-line is reading from a file or from stdin in a CGI program or pipe, it will return nil when input is exhausted.

stdin 上で read-line を使う時の行の長さは 2048 に制限され、より速く実行されます。
When using read-line on stdin, line length is limited to 2048 characters and performance is much faster.

(print "Enter a num:")
(set 'num (int (read-line)))

(set 'in-file (open "afile.dat" "read"))
(while (read-line in-file)
        (write-line))   
(close in-file)

最初の例では、キーボードからの入力を読み取り、数値に変換します。 二番目の例では、ファイルが一行ずつ読み取られ、スクリーン上に表示されます。 write-line 宣言文は、最後の read-line 操作の結果がシステムの内部バッファに保存されていることを利用しています。 つまり、write-line が引数なしで使われ、最後の read-line バッファの内容がスクリーンに書き込まれていることになります。
The first example reads input from the keyboard and converts it to a number. In the second example, a file is read line-by-line and displayed on the screen. The write-line statement takes advantage of the fact that the result from the last read-line operation is stored in a system internal buffer. When write-line is used without argument, it writes the contents of the last read-line buffer to the screen.

このバッファから取り出すための関数 current-line も見てください。
See also the current-line function for retrieving this buffer.



read-utf8

syntax: (read-utf8 int-file)

ファイル・ハンドル int-file で指定されたファイルから、UTF-8 文字を一文字読み取ります。 ファイル・ハンドルは、先行する open 操作から得られます。 各 read-utf8 は UTF-8文字で得られたバイト数分、ファイルポインタを進めます。 ファイルが終わりに達した時、nil が返されます。
Reads an UTF-8 character from a file specified by the file handle in int-file. The file handle is obtained from a previous open operation. Each read-utf8 advances the file pointer by the number of bytes contained in the UTF-8 character. Once the end of the file is reached, nil is returned.

この関数の戻り値は整数値で、その数値に関数 char を使えば、表示可能な UTF-8 文字に変換できます。
The function returns an integer value which can be converted to a displayable UTF-8 character string using the char function.

(set 'fle (open "utf8text.txt" "read"))
(while (setq chr (read-utf8 fle))
	(print (char chr)))

この例は、UTF-8 エンコード・テキストからなるファイルを読み取り、それをターミナル・スクリーンに表示します。
The example reads a file containing UTF-8 encoded text and displays it to the terminal screen.



reader-event

syntax: (reader-event [sym-event-handler | func-event-handler])
syntax: (reader-event nil)

newLISPリーダーの翻訳と評価のプロセス間をフックするためのイベント・ハンドラを指定できます。 newLISP が式を翻訳して評価する前に、sym-event-handlerfunc-event-handler で指定された関数が呼び出されます。 イベント・ハンドラが評価される前の式を変換できるのです。
An event handler can be specified to hook between newLISP's reader, translation and evaluation process. The function specified in sym-event-handler or func-event-handler gets called after newLISP translates an expression and before evaluating it. The event handler can do transformation on the expression before it gets evaluated.

イベントに nil を指定すると、初期のデフォルト状態にリセットされます。
Specifying nil for the event will reset it to the initial default state.

次の一行 reader-event は、インターラクティブ・シェルをトレーサー付きに拡張しています:
The following one-liner reader-event could be used to enhance the interactive shell with a tracer:

>(reader-event (lambda (ex) (print " => " ex)))
$reader-event
> (+ 1 2 3)
 => (+ 1 2 3) 
6
>

インターセプトされた式は変化せずに渡されていますが、出力が改良されています。
The expression intercepted passes through unchanged, but output is enhanced.

関数 loadeval-string で、各s式が読み取られる度に、リーダー・イベント機能が呼び出されます。
The reader event function will be called after each reading of an s-expression by the load or eval-string function.

10.5.8 以前のバージョンでは、拡張 macro 機能を定義するためにモジュール・ファイル macro.lsp を使用していました。 バージョン 10.5.8 からの newLISP は、同じように動作する組込関数 macro を持ち、ファイルのロードやソースの読み込みがより早くなっています。
In versions previous to 10.5.8 reader-event was used to define a macro expansion function in the module file macro.lsp. Starting version 10.5.8, newLISP has macro as a built-in function behaving the same, but much faster when loading files and reading source.



real-path

syntax: (real-path [str-path])
syntax: (real-path str-exec-name true)

第一構文の str-path は、与えられた相対ファイル・パス からフル・パスを返します。 パスが与えられないと "."(カレント・ディレクトリ)になります。
In the first syntax real-path returns the full path from the relative file path given in str-path. If a path is not given, "." (the current directory) is assumed.

(real-path)   "/usr/home/fred"  ; current directory
(real-path "./somefile.txt")
 "/usr/home/fred/somefile.txt"

第二構文の real-pathstr-exe-name で与えられる実行ファイルのフル・パスを返します。 UNIX や Windows システムにおいて、この構文は環境変数 PATH に依存します。
In the second syntax real-path returns the full path for an executable found given in str-exe-name. This syntax relies on an environment variable PATH defined on UNIX and Windows systems.

(real-path "make" true)  "/usr/bin/make"

出力の長さは、OS で許されているパスの最大長で制限されます。 real-path は、失敗する(すなわち、パスが存在しない)と nil を返します。
The output length is limited by the OS's maximum allowed path length. If real-path fails (e.g., because of a nonexistent path), nil is returned.



receive !

syntax: (receive int-pid sym-message)
syntax: (receive)

この関数の第一構文は、spawn で起動した子プロセスとその親プロセス間のメッセージ交換に使われます。 受信したメッセージは、sym-message の内容になります。
In the first syntax, the function is used for message exchange between child processes launched with spawn and their parent process. The message received replaces the contents in sym-message.

関数は起動される度に int-pid の受信キューからメッセージを一つ読み取ります。 キューが空の時は nil が返ります。
The function reads one message from the receiver queue of int-pid for each invocation. When the queue is empty, nil is returned.

; sending process
(send spid "hello")   true

; receiving process
(receive pid msg)     true
msg                   "hello"

関数 receive をブロッキングしてメッセージが届くまで待たせるには、次の形をとります:
To make receive blocking and wait for arriving messages, use the following form:

; wait until a message can be read
(until (receive pid msg))

キューからメッセージを読みだせるようになるまで、この関数はループします。
The function will loop until a message can be read from the queue.

この関数の第二構文は、親プロセスからのメッセージを保留している子プロセスの全リストを返します:
In the second syntax, the function returns a list of all child processes with pending messages for the parent process:

; read pending messages from child processes
(dolist (pid (receive))
    (receive pid msg)
    (println "received message: " msg " from:" pid)
)

(receive) で返される子プロセス ID のリストには、読み取られていないメッセージを送信キューに持っているプロセスの PID のみが入ります。 これにより、保留中のメッセージが子プロセスのメッセージ・キューにあることが常に保証され、(receive pid msg) 宣言文がノン・ブロッキングで実行されます。
The list of child process IDs returned by (receive) only contains PIDs of processes which have unread messages in their send queues. The (receive pid msg) statement now can be issued non-blocking, because it always is guaranteed to find a pending message in a child's message queue.

関数 receive は MS Windows では使えません。
The receive function is not available on MS Windows.

この関数と例題のより詳細な議論は、関数 send を見てください。
For a more detailed discussion of this function and examples, see the send function.



ref

syntax: (ref exp-key list [func-compare [true]])

ref はキー式 exp-keylist 中で検索し、整数インデックスのリストを返します。 exp-key が見つからない時は空リストを返します。 インデックスのリストが使える pushpop と一緒に、ref を使うことができます。
ref searches for the key expression exp-key in list and returns a list of integer indices or an empty list if exp-key cannot be found. ref can work together with push and pop, both of which can also take lists of indices.

デフォルトの ref は、式が等しいかどうかをチェックします。 より複雑な比較関数を func-compare に使うこともできます。 比較関数を前もって定義しておくことも可能です。 この関数が関数内部で第二引数しか使わない場合でも、常に引数を二つとることに注意してください(訳注:第一引数に exp-key が、第二引数に list の要素が入ります)。
By default, ref checks if expressions are equal. With func-compare, more complex comparison functions can be used. The comparison function can be a previously defined function. Note that this function always takes two arguments, even if only the second argument is used inside the function.

オプションの true パラメータがある時は、インデックス・ベクトルの代わりに見つかった要素が返ります。
When the optional true parameter is present, the element found is returned instead of the index vector.

; get index vectors for list elements

(set 'pList '(a b (c d (x) e)))

(ref 'x pList)     (2 2 0)

(ref '(x) pList)    (2 2)

; the key expression is in a variable

(set 'p '(c d (x) e))

(ref p pList)    (2)

; indexing using the vector returned from ref

(set 'v (ref '(x) pList))  (2 2)

(pList v)  (x)

; if nothing is found, nil is returned

(ref 'foo plist)   nil

; not specifying a comparison functor assumes =

(set 'L '(a b (c d (e) f)))

(ref 'e L)       (2 2 0)
(ref 'e L =)     (2 2 0)

; a is the first symbol where e is greater

(ref 'e L >)   (0)

; return the element instead of the index

(ref 'e L > true)   a

; use an anonymous comparison function

(ref 'e L (fn (x y) (or (= x y) (= y 'd))))       (2 1)

(ref 'e L (fn (x y) (or (= x y) (= y 'd))) true)  d

次の例は、文字列に対する正規表現と同じくらい強力な検索を提供する matchunify の使い方を示しています:
The following example shows the use of match and unify to formulate searches that are as powerful as regular expressions are for strings:

(set 'L '((l 3) (a 12) (k 5) (a 10) (z 22)))

; use match as a comparison function

(ref '(a ?) L match)  (1)

; use unify as a comparison function

(set 'L '( ((a b) (c d)) ((e e) (f g)) ))

(ref '(X X) L unify)       (1 0)

(ref '(X g) L unify)       (1 1)

(ref '(X g) L unify true)  (f g)

unify と一緒の '(X X) パターンは、二つの要素が同じリスト・ペアを検索します。 unify のパターン '(X g) は、二番目の要素がシンボル g であるリスト・ペアを検索します。 パターンには、評価されないようにクォートを付けます。
The '(X X) pattern with unify searches for a list pair where the two elements are equal. The unify pattern '(X g) searches for a list pair with the symbol g as the second member. The patterns are quoted to protect them from evaluation.

デフォルト・ファンクタでリストを渡すと:
Pass the list as a default functor:

(set 'C:C '(a b (c d) e f))

(ref 'd C)   (2 1)

リストを渡すには、コンテキストを使った参照が適切です。 参照によるデータの受け渡し の章も見てください。
This is suitable when passing lists by reference using a context. See also the chapter Passing data by reference.

入れ子リストでのキー式を全て検索する関数 ref-all も見てください。
See also the ref-all function, which searches for all occurrences of a key expression in a nested list.



ref-all

syntax: (ref-all exp-key list [func-compare [true]])

ref のように動作しますが、list 中で見つかった exp-key の全インデックス・ベクトルをリストで返します。
Works similarly to ref, but returns a list of all index vectors found for exp-key in list.

オプションの true パラメータがある時は、インデックス・ベクトルの代わりに見つかった要素が返ります。
When the optional true parameter is present, the elements found is returned of the index vectors.

デフォルトの ref-allは、式が等しいかどうかをチェックします。 より複雑な比較関数を func-compare に使うこともできます。
By default, ref-all checks if expressions are equal. With func-compare, more complex comparison functions can be used.

システム変数 $count には、見つかった要素数が入ります。
The system variable $count counts the number of elements found.

(set 'L '(a b c (d a f (a h a)) (k a (m n a) (x))))

(ref-all 'a L)  ((0) (3 1) (3 3 0) (3 3 2) (4 1) (4 2 2))

; the index vector returned by ref-all can be used to index the list

(L '(3 1))  a

; mapped implicit indexing of L 

(map 'L (ref-all 'a L))  (a a a a a a)

; with comparison operator

(set 'L '(a b c (d f (h l a)) (k a (m n) (x))))

; not specifying a comparison functor assumes =

(ref-all 'c L)        ((2))
(ref-all 'c L =)      ((2))

; look for all elements where c is greater

(ref-all 'c L >)        ((0) (1) (3 2 2) (4 1))
(ref-all 'c L > true)   (a b a a)


; use an anonymous function to compare

(ref-all 'a L (fn (x y) (or (= x y) (= y 'k))))  
 ((0) (3 2 2) (4 0) (4 1))

; the key is nil because the comparison function only looks at the second argument

(ref-all nil L (fn (x y) (> (length y) 2)))      
 ((3) (3 2) (4))

; define the comparison functions first

(define (is-long? x y) (> (length y) 2)) ; the x gets occupied by 'nil

(ref-all nil L is-long?)      ((3) (3 2) (4))

(define (is-it-or-d x y) (or (= x y) (= y 'd)))

(set 'L '(a b (c d (e) f)) )

(ref-all 'e L is-it-or-d)   ((2 1) (2 2 0))

比較関数を前もって定義しておくことも可能です。 比較関数は、(is-long? を使った例のように)関数の中で第二引数しか使わない場合でも、常に引数を二つ持つことに注意してください (訳注:第一引数に exp-key が、第二引数に list の要素が入ります)。
The comparison function can be a previously defined function. Note that the comparison function always takes two arguments, even if only the second argument is used inside the function (as in the example using is-long?).

関数 matchunify を使うと、文字列に対する正規表現と同じくらい強力なリスト検索が可能です。
Using the match and unify functions, list searches can be formulated that are as powerful as regular expression searches are for strings.

(set 'L '((l 3) (a 12) (k 5) (a 10) (z 22)) )

; look for all pairs staring with the symbol a

(ref-all '(a ?) L match)       ((1) (3))
(ref-all '(a ?) L match true)  ((a 12) (a 10))

; look for all pairs where elements are equal

(set 'L '( ((a b) (c d)) ((e e) (f g)) ((z) (z))))

(ref-all '(X X) L unify)       ((1 0) (2))
(ref-all '(X X) L unify true)  ((e e) ((z) (z)))

; look for all pairs where the second element is the symbol g

(set 'L '( ((x y z) g) ((a b) (c d)) ((e e) (f g)) ))

(ref-all '(X g) L unify)       ((0) (2 1))
(ref-all '(X g) L unify true)  (((x y z) g) (f g))

関数 ref も見てください。
See also the ref function.



regex

syntax: (regex str-pattern str-text [regex-option [int-offset]])

str-pattern で指定されたパターンの Perl コンパチブル正規表現 (PCRE) 検索を str-text に対して実行します。 同じ正規表現パターン・マッチングが、文字列を扱う関数 directoryfindfind-allparsereplacesearch でもサポートされています。
Performs a Perl Compatible Regular Expression (PCRE) search on str-text with the pattern specified in str-pattern. The same regular expression pattern matching is also supported in the functions directory, find, find-all, parse, replace, and search when using these functions on strings.

regex は、一致した文字列と部分文字列、テキスト中の各文字列の開始位置と長さのリストを返します。 一致しなかった時は nil を返します。 オフセットの数値は、後に続く手続きの中で使えます。
regex returns a list with the matched strings and substrings and the beginning and length of each string inside the text. If no match is found, it returns nil. The offset numbers can be used for subsequent processing.

追加で、後で説明する正規表現の制御用 regex-option を指定できます。 オプションは、数値と文字列による文字のどちらかで与えられます。
Addtionally an regex-option can be specified to control certain regular expression options explained later. Options can be given either by numbers or letters in a string.

追加の int-offset パラメータは、マッチ検索の開始が文字列の先頭ではなくオフセット位置からであることを regex に知らせます。
The additional int-offset parameter tells regex to start searching for a match not at the beginning of the string but at an offset.

regex-option が無い時、regex の結果のオフセットと長さは UTF-8 版 newLISP であってもバイト単位で与えられます。 regex-option に PCRE_UTF8 オプションを指定した時のみ、オフセットと長さが UTF8 文字単位で報告されます。
When no regex-option is present, the offset and length numbers in the regex results are given based bytes even when running the UTF-8 enabled version of newLISP. When specifying the PCRE_UTF8 option in regex-option only offset and length are reported in UTF8 characters.

regex は、見つかった式と部分式を変数 $0, $1, $2– にもセットします。 他の newLISP シンボルと同じように、これらの変数とその等価式 ($ 0), ($ 1), ($ 2)– は、続く手続きの中で他の newLISP 式と同じように使えます。
regex also sets the variables $0, $1, and $2— to the expression and subexpressions found. Just like any other symbol in newLISP, these variables or their equivalent expressions ($ 0), ($ 1), and ($ 2)— can be used in other newLISP expressions for further processing.

正規表現を使った関数は、一致が見つからなかった時には変数 $0, $1 ... $15nil にリセットしません(訳注:この場合、前に一致した内容が入ってくることがありますので注意してください。regex の戻り値が nil だったなら、変数 $0, $1 ... $15 は使わない方が賢明です)。
Functions using regular expressions will not reset the $0, $1 ... $15 variables to nil when no match is found.

(regex "b+" "aaaabbbaaaa")   ("bbb" 4 3)

; case-insensitive search option 1
(regex "b+" "AAAABBBAAAA" 1)   ("BBB" 4 3) 

(regex "[bB]+" "AAAABbBAAAA" )   ("BbB" 4 3)

(regex "http://(.*):(.*)" "http://nuevatec.com:80") 
 ("http://nuevatec.com:80" 0 22 "nuevatec.com" 7 12 "80" 20 2)

$0   "http://nuevatec.com:80"
$1   "nuevatec.com"
$2   "80"

(dotimes (i 3) (println ($ i)))
http://nuevatec.com:80
nuevatec.com
80
 "80"

二番目の例はオプションの使い方を示し、三番目の例は検索パターン中の括弧によってマークされた二つの部分式による複雑な分解を実演しています。 最後の例では、式と部分式がシステム変数 $0$2 あるいは 等価式 ($ 0)($ 2) を使って取り出されています。
The second example shows the usage of extra options, while the third example demonstrates more complex parsing of two subexpressions that were marked by parentheses in the search pattern. In the last example, the expression and subexpressions are retrieved using the system variables $0 to $2 or their equivalent expression ($ 0) to ($ 2).

バックスラッシュ文字を含む文字列を囲むために ""(引用符)が使われている時は、正規表現パターン中でバックスラッシュを二重にする必要があります。 代わりの文字列の区切りに、{ }(波括弧)か [text][/text](テキスト・タグ)が使えます。 これらの場合には、余計なバックスラッシュが要求されません。
When "" (quotes) are used to delimit strings that include literal backslashes, the backslash must be doubled in the regular expression pattern. As an alternative, { } (curly brackets) or [text] and [/text] (text tags) can be used to delimit text strings. In these cases, no extra backslashes are required.

バックスラッシュでエスケープされる newLISP 文字(例えば、引用符 \" とか \n とか)は、引用符で囲まれている正規表現パターン内でも(訳注:バックスラッシュを)二重化する必要はありません。
Characters escaped by a backslash in newLISP (e.g., the quote \" or \n) need not to be doubled in a regular expression pattern, which itself is delimited by quotes.

;; double backslash for parentheses and other special char in regex
(regex "\\(abc\\)" "xyz(abc)xyz")   ("(abc)" 3 5)
;; double backslash for backslash (special char in regex)
(regex "\\d{1,3}" "qwerty567asdfg")   ("567" 6 3)

;; one backslash for quotes (special char in newLISP)
(regex "\"" "abc\"def")   ("\"" 3 1)     

;; brackets as delimiters
(regex {\(abc\)} "xyz(abc)xyz")   ("(abc)" 3 5)  

;; brackets as delimiters and quote in pattern
(regex {"} "abc\"def")   ("\"" 3 1)     

;; text tags as delimiters, good for multiline text in CGI
(regex [text]\(abc\)[/text] "xyz(abc)xyz")   ("(abc)" 3 5)  
(regex [text]"[/text] "abc\"def")            ("\"" 3 1) 

引用符の代わりに波括弧かテキスト・タグがパターン文字列の囲みに使われている時は、一個のバックスラッシュで十分です。 そして、パターンと文字列はそのままの形で正規表現ルーチンに渡されます。 波括弧で区切られたパターン内で波括弧が使われる時は、次のように内部の波括弧がバランスされていなければなりません:
When curly brackets or text tags are used to delimit the pattern string instead of quotes, a simple backslash is sufficient. The pattern and string are then passed in raw form to the regular expression routines. When curly brackets are used inside a pattern itself delimited by curly brackets, the inner brackets must be balanced, as follows:

;; brackets inside brackets are balanced
(regex {\d{1,3}} "qwerty567asdfg")   ("567" 6 3) 

次の定数が regex-option で使えます。 いくつかのオプションは、バイナリか |(パイプ)演算子を使って結合できます。 例えば、(| 1 4) は、オプション 14 を結合します(訳注:|ビット OR 演算子です)。 大文字の名称は PCRE regex ドキュメントで使われているもので、init.lsp に前もって定義しておけばよいでしょう。
The following constants can be used for regex-option. Several options can be combined using a binary or | (pipe) operator. E.g. (| 1 4) would combine options 1 and 4 or "is" when using letters for the two options.

最後の二つのオプションは newLISP 専用オプションです。REPLACE_ONCE オプションは replace でのみ使え、他の PCRE オプションと組み合わせることができます。
The last two options are specific for newLISP. The REPLACE_ONCE option is only to be used in replace; it can be combined with other PCRE options.

複数のオプションは + (プラス) や | (or) 演算子を使って組み合わせることができます。例えば: (| PCRE_CASELESS PCRE_DOTALL) や文字を使ったオプション指定 "is"
Multiple options can be combined using a + (plus) or | (or) operator, e.g.: (| PCRE_CASELESS PCRE_DOTALL) or "is" when using letters as options.

PCRE namenodescription
PCRE_CASELESS1 or i大文字を小文字として扱う
treat uppercase like lowercase
PCRE_MULTILINE2 or mPerl の /m のように改行で検索が制限されます。
(訳注: 行頭 (^) と行末 ($) が一行毎に使えるようになる )
limit search at a newline like Perl's /m
PCRE_DOTALL4 or s. (dot) が改行にもマッチします。
. (dot) also matches newline
PCRE_EXTENDED8 or x文字クラス内以外の空白文字を無視します。
ignore whitespace except inside char class
PCRE_ANCHORED16 or A(訳注:検索位置を)文字列の先頭に固定します。
anchor at the start
PCRE_DOLLAR_ENDONLY32 or D$ は、改行の前ではない文字列の最後での一致を試みます。
$ matches at end of string, not before newline
PCRE_EXTRA64この付加機能は、現在使えません。
additional functionality currently not used
PCRE_NOTBOL128行の先頭でない最初の文字が ^ で一致しなくなります。
(訳注:PCRE_MULTILINE と一緒に使う)
first ch, not start of line; ^ shouldn't match
PCRE_NOTEOL256行の終わりでない最後の文字が $ で一致しなくなります。
(訳注:PCRE_MULTILINE と一緒に使う)
last char, not end of line; $ shouldn't match
PCRE_UNGREEDY512 or U量指定子の貪欲さを反転します。
(訳注:最小の一致を見つける時に使う)
invert greediness of quantifiers
PCRE_NOTEMPTY1024空文字列は、無効になります。
empty string considered invalid
PCRE_UTF82048 or uパターンと文字列が、UTF-8文字になります。
pattern and strings as UTF-8 characters
REPLACE_ONCE0x8000replaceで使われた時のみ、一回だけ置換されます。
replace only one occurrence only for use in replace
PRECOMPILED0x10000 or pパターンは、プリ・コンパイルされ、RREPLACE_ONCE 0x8000とだけ結合できます。
pattern is pre-compiled, can only be combined with RREPLACE_ONCE 0x8000

PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, PCRE_EXTENDED オプションの設定は、 "(?" と ")" で囲まれたオプション文字シーケンスによるパターン内でも変更できます。 オプション文字は、次の通り:
The settings of the PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and PCRE_EXTENDED options can be changed from within the pattern by a sequence of option letters enclosed between "(?" and ")". The option letters are:

ifor PCRE_CASELESS
mfor PCRE_MULTILINE
sfor PCRE_DOTALL
xfor PCRE_EXTENDED

正規表現構文は多くの特殊文字と形式により非常に複雑で特徴に富んでいるので、気を付けてください。 どうか、詳細を書籍か PCRE マニュアル・ページで調べてください。 多くの PERL 本や Linux または Unix の紹介は正規表現の章を持っています。 さらなるリファレンスとマニュアルのページとして、http://www.pcre.org を見てください。
Note that regular expression syntax is very complex and feature-rich with many special characters and forms. Please consult a book or the PCRE manual pages for more detail. Most PERL books or introductions to Linux or Unix also contain chapters about regular expressions. See also http://www.pcre.org for further references and manual pages.

regex-comp を使えば、正規表現パターンの反復の多いパターンを高速用にプリコンパイルできます。
Regular expression patterns can be precompiled for higher speed when using changing repetitive patterns with regex-comp.



regex-comp

syntax: (regex-comp str-pattern [int-option])

newLISP は自動的に正規表現パターンをコンパイルし、反復の多いパターン検索を高速化するために最後の編集をキャッシュします。 パターンを次から次へと変化させて幾重にも繰り返すならば、最後のパターンのキャッシュでも十分ではありません。 regex-comp は、正規表現検索の高速化のために反復の多いパターンをプリ・コンパイルするために使えます:
newLISP automatically compiles regular expression patterns and caches the last compilation to speed up repetitive pattern searches. If patterns change from one to the next, but are repeated over and over again, then the caching of the last pattern is not sufficient. regex-comp can be used to pre-compile repetitive patterns to speed up regular expression searches:

; slower without pre-compilation

(dolist (line page)
	(replace pattern-str1 line repl1 0)
	(replace pattern-str2 line repl2 512)
)

; fast with pre-compilation and option 0x10000

(set 'p1 (regex-comp pattern-str1))
(set 'p2 (regex-comp pattern-str2 512))

(dolist (line page)
	(replace p1 line repl1 0x10000)
	(replace p2 line repl2 0x10000)
)

正規表現を使う関数でパターンのプリ・コンパイルを使う時は 0x10000 をセットして、プリ・コンパイルされたパターンの使用を合図します。 通常の正規パターン・オプションは regex-comp でプリ・コンパイルする際に指定します。 replace で使う時のみ、0x10000 オプションを一回だけの置換を指定するオプション 0x8000 と結合できます。
When using pre-compiled patterns in any of the functions using regular expressions, the option number is set to 0x10000 to signal that pre-compiled patterns are used. Normal pattern options are specified during pre-compilation with regex-comp . The 0x10000 option can only be combined with 0x8000, the option used to specify that only one replacement should be made when using replace.

関数 ends-with は内部に非コンパイル・パターンを付加しようするので、コンパイル・パターンと一緒には使うべきではありません。
The function ends-with should not be used with compiled patterns, as it tries to append to an un-compiled pattern internally.



remove-dir

syntax: (remove-dir str-path)

str-path で指定されたパス名のディレクトリを削除します。 remove-dir を成功させるには、ディレクトリが空である必要があります。 失敗すると、nil を返します。
Removes the directory whose path name is specified in str-path. The directory must be empty for remove-dir to succeed. Returns nil on failure.

(remove-dir "temp")

カレント・ディレクトリの temp を削除します。
Removes the directory temp in the current directory.



rename-file

syntax: (rename-file str-path-old str-path-new)

パス名 str-path-old で与えられたファイルやディレクトリを str-path-new で与えられた名前に変更します。 操作の結果次第で、niltrue が返ります。
Renames a file or directory entry given in the path name str-path-old to the name given in str-path-new. Returns nil or true depending on the operation's success.

(rename-file "data.lisp" "data.backup")


replace !

syntax: (replace exp-key list exp-replacement [func-compare])
syntax: (replace exp-key list)

syntax: (replace str-key str-data exp-replacement)
syntax: (replace str-pattern str-data exp-replacement regex-option)

List replacement(リストの置換)

replace は第二引数がリストなら、リスト list の中で式 exp-key に等しい要素を全て置換します。 要素は exp-replacement に置換されます。 exp-replacement が無い時は、list から exp-key が削除されます。
If the second argument is a list, replace replaces all elements in the list list that are equal to the expression in exp-key. The element is replaced with exp-replacement. If exp-replacement is missing, all instances of exp-key will be deleted from list.

replace が破壊的であることに注意してください。 渡されたリストは変更され、その変更されたリストが返ります。 関数から戻った時、置換された数はシステム変数 $count に入ります。 置換式を実行中、アナフォリック・システム変数 $it には置換された式が入っています。
Note that replace is destructive. It changes the list passed to it and returns the changed list. The number of replacements made is contained in the system variable $count when the function returns. During executions of the replacement expression, the anaphoric system variable $it is set to the expression to be replaced.

オプションで、func-compare に比較演算子かユーザ定義関数を指定できます。 デフォルトで、func-compare=(等号記号)です。
Optionally, func-compare can specify a comparison operator or user-defined function. By default, func-compare is the = (equals sign).

;; list replacement

(set 'aList '(a b c d e a b c d))

(replace 'b aList 'B)   (a B c d e a B c d)
aList   (a B c d e a B c d)
$count  2  ; number of replacements

;; list replacement with special compare functor/function

; replace all numbers where 10 < number
(set 'L '(1 4 22 5 6 89 2 3 24))

(replace 10 L 10 <)  (1 4 10 5 6 10 2 3 10)
$count  3

; same as:

(replace 10 L 10 (fn (x y) (< x y)))  (1 4 10 5 6 10 2 3 10)

; change name-string to symbol, x is ignored as nil

(set 'AL '((john 5 6 4) ("mary" 3 4 7) (bob 4 2 7 9) ("jane" 3)))

(replace nil AL (cons (sym ($it 0)) (rest $it)) 
                (fn (x y) (string? (y 0)))) ; parameter x = nil not used
 ((john 5 6 4) (mary 3 4 7) (bob 4 2 7 9) (jane 3))

; use $count in the replacement expression
(replace 'a '(a b a b a b) (list $count $it) =)   ((1 a) b (2 a) b (3 a) b)

関数 matchunify を使うと、正規表現文字列検索と同じくらい強力にリスト検索が定型化されます:
Using the match and unify functions, list searches can be formulated that are as powerful as regular expression string searches:

; calculate the sum in all associations with 'mary

(set 'AL '((john 5 6 4) (mary 3 4 7) (bob 4 2 7 9) (jane 3)))

(replace '(mary *)  AL (list 'mary (apply + (rest $it))) match)
 ((john 5 6 4) (mary 14) (bob 4 2 7 9) (jane 3))
$count  1

; make sum in all expressions

(set 'AL '((john 5 6 4) (mary 3 4 7) (bob 4 2 7 9) (jane 3)))

(replace '(*) AL (list ($it 0) (apply + (rest $it))) match)
 ((john 15) (mary 14) (bob 22) (jane 3))
$count  4

; using unify, replace only if elements are equal
(replace '(X X) '((3 10) (2 5) (4 4) (6 7) (8 8)) (list ($it 0) 'double ($it 1)) unify)
 ((3 10) (2 5) (4 double 4) (6 7) (8 double 8))
 

List removal(リストからの削除)

最後の形式の replace は、二つの引数 explist のみを持ちます。 この形式は、list 中に見つかった全ての exp を削除します。
The last form of replace has only two arguments: the expression exp and list. This form removes all exps found in list.

;; removing elements from a list

(set 'lst '(a b a a c d a f g))
(replace 'a lst)   (b c d f g)
lst                (b c d f g)

$count  4

String replacement without regular expression(正規表現無しの文字列置換)

全引数が文字列なら、replacestr-data 中に出現した全ての str-keyexp-replacement の評価値に置き換えます。 式 exp-replacement は、置換対象用に全て評価されます。 置換した数はシステム変数 $0 に入ります。 この形式の replace は、バイナリ 0(ゼロ)も処理できます。
If all arguments are strings, replace replaces all occurrences of str-key in str-data with the evaluated exp-replacement, returning the changed string. The expression in exp-replacement is evaluated for every replacement. The number of replacements made is contained in the system variable $0. This form of replace can also process binary 0s (zeros).

;; string replacement
(set 'str "this isa sentence")
(replace "isa" str "is a")   "this is a sentence"

$count  1

Regular expression replacement(正規表現による置換)

第四パラメータの存在は、正規表現検索が実行されることを意味します。str-pattern に正規表現パターンを、regex-option にオプション番号(例えば、標準 Perl コンパチブル正規表現 (PCRE) 検索で大文字・小文字同一視をするかしないかを指定する 1(一)やオプションなしの 0(ゼロ)とか)を指定します。 (訳注:正規表現の)詳細は、regex を見てください。
The presence of a fourth parameter indicates that a regular expression search should be performed with a regular expression pattern specified in str-pattern and an option number specified in regex-option (e.g., 1 (one) for case-insensitive searching or 0 (zero) for a standard Perl Compatible Regular Expression (PCRE) search without options). See regex above for details.

デフォルトでは、検索パターン中に行頭指定が含まれていても、replace は検索文字列の全ての出現を置換します。 各置換の後、str-data の新しい位置からの新しい検索が開始されます。 regex-option にオプション・ビット 0x8000 を設定すれば、replace は最初の出現だけを置換します。 変更された文字列が返ります。
By default, replace replaces all occurrences of a search string even if a beginning-of-line specification is included in the search pattern. After each replace, a new search is started at a new position in str-data. Setting the option bit to 0x8000 in regex-option will force replace to replace only the first occurrence. The changed string is returned.

正規表現を使った replace は、見つかった式と部分式の内容を内部変数 $0, $1, $2– にセットします。 アナフォリック・システム変数 $itに は、$0 と同じ内容がセットされます。 これらを使って、置換中に見つかる内容に応じた置換を実現できます。 シンボル $it, $0, $1>$2– は、他のシンボルと同様に式として使えます。 置換式が文字列以外に評価された時は、置換が行われません。 変数の内容のアクセスには、代替方法として ($ 0), ($ 1), ($ 2), 等々も使えます。 この方法は、インデックスによるアクセスを許可しています(例えば ($ i)、ここで i は整数)。
replace with regular expressions also sets the internal variables $0, $1, and $2— with the contents of the expressions and subexpressions found. The anaphoric system variable $it is set to the same value as $0. These can be used to perform replacements that depend on the content found during replacement. The symbols $it, $0, $1, and $2— can be used in expressions just like any other symbols. If the replacement expression evaluates to something other than a string, no replacement is made. As an alternative, the contents of these variables can also be accessed by using ($ 0), ($ 1), ($ 2), and so forth. This method allows indexed access (e.g., ($ i), where i is an integer).

全ての置換終了後、置換した数がシステム変数 $0 に入ります。
After all replacements are made, the number of replacements is contained in the system variable $count.

;; using the option parameter to employ regular expressions

(set 'str "ZZZZZxZZZZyy")      "ZZZZZxZZZZyy"
(replace "x|y" str "PP" 0)   "ZZZZZPPZZZZPPPP"
str                            "ZZZZZPPZZZZPPPP"

;; using system variables for dynamic replacement

(set 'str "---axb---ayb---")
(replace "(a)(.)(b)" str (append $3 $2 $1) 0) 
 "---bxa---bya---"

str   "---bxa---bya---"

;; using the 'replace once' option bit 0x8000

(replace "a" "aaa" "X" 0)   "XXX"

(replace "a" "aaa" "X" 0x8000)   "Xaa"

;; URL translation of hex codes with dynamic replacement

(set 'str "xxx%41xxx%42")
(replace "%([0-9A-F][0-9A-F])" str 
               (char (int (append "0x" $1))) 1)

str   "xxxAxxxB"

$count  2

関数 setfnthfirstlast と一緒に使っても、リストの内容変更ができます。
The setf function together with nth, first or last can also be used to change elements in a list.

正規表現を使える他の関数 directoryfindfind-allparseregexsearch も見てください。
See directory, find, find-all, parse, regex, and search for other functions using regular expressions.



reset

syntax: (reset)
syntax: (reset true)
syntax: (reset int-max-cells)

第一構文の reset は、trace モードをオフにして、コンテキスト/名前空間を MAIN に切り替え、評価のトップ・レベルに戻ります。 reset は、トップ・レベルの変数環境をスタックに保存されていた変数環境に戻します。 このことは エラー "user reset - no error" も引き起こしますが、ユーザ定義のエラー・ハンドラで報告させることも可能です。 バージョン 10.5.5 からは、コマンド・ライン・パラメータ処理中でも中断します。
In the first syntax, reset returns to the top level of evaluation, switches the trace mode off, and switches to the MAIN context/namespace. reset restores the top-level variable environment using the saved variable environments on the stack. It also throws an error "user reset - no error" which can be reported with user defined error handlers. Since version 10.5.5 reset also interrupts command line parameter processing.

reset は全てのセル空間を通るので、重い負荷のかかったシステムでは数秒かかるかもしれません。
reset walks through the entire cell space, which may take a few seconds in a heavily loaded system.

エラー条件が起こると、reset が自動的に起動します。
reset occurs automatically after an error condition.

第二構文の reset はカレント・プロセスを止めて、同じコマンド・ライン・パラメータで新しい newLISP プロセスを開始します。 このモードは単に newlisp ではなく、例えば /usr/local/bin/newlisp のようにフルパス名の newLISP を使ってのみ開始され、作動します。 このモードは、MS Windows では利用できません。
In the second syntax, reset will stop the current process and start a new clean newLISP process with the same command-line parameters. This mode will only work when newLISP was started using its full path-name, e.g. /usr/local/bin/newlisp instead of only newlisp. This mode is not available on MS Windows.

第二構文の reset はシステムに許される最大セル数を変更します。 この数は sys-info のリスト中二番目にあります。 64 ビットの newLISP では一セルが 32 バイト占有し、32 ビット版では 16 バイトです。 これには文字列のメモリは含まれていません、セルが文字列を指し示していますけど。
In the third syntax. reset will change the maximum cell count allowed in the system. This number is also reported as the second number in the list by sys-info. On 64-bit newLISP one lisp cell occupies 32 bytes, or 16 bytes on the 32-bit version. This does not include string memory, which may be pointed to by cells.

最小セル数は 4095 個です。試しにセル数を 4095 に指定してみましょう。 それ以上の割り当てを試すと、プログラムは終了します。
The minimum cell count is 4095, trying to specify less will set it to 4095. The program will exit when trying to allocate more.

(sys-info)   (437 576460752303423488 409 1 0 2048 0 60391 10602 1411)

; allocate about 1 Mbyte of cell memory on 64-bit newlisp
(reset 32768)  true

(sys-info)   (437 32768 409 1 0 2048 0 60392 10602 1411)

最大セル数のリセットではシステムは再開始になりませんし、どの時点でも行うことができます。 セル・メモリーは最小構成でもある 4095 セルのブロック単位で割り当てられます。
Resetting the maximum cell count will not restart the system and can be done at any point in a program. Cell memory is allocated in blocks of 4095 cells, which is also initial minimum configuration.



rest utf8

syntax: (rest list)
syntax: (rest array)
syntax: (rest str)

リストや文字列の最初だけ除いた全てを返します。 rest は、他の Lisp 方言の cdrtail と等価です。
Returns all of the items in a list or a string, except for the first. rest is equivalent to cdr or tail in other Lisp dialects.

(rest '(1 2 3 4))             (2 3 4)
(rest '((a b) c d))           (c d)
(set 'aList '(a b c d e))     (a b c d e)
(rest aList)                  (b c d e)
(first (rest aList))          b
(rest (rest aList))           (d e)
(rest (first '((a b) c d)))   (b)

(set 'A (array 2 3 (sequence 1 6)))
 ((1 2) (3 4) (5 6))

(rest A)   ((3 4) (5 6))

(rest '())  ()

第二構文の rest は、文字列 str の最初の文字以外の全てを返します。
In the second version, rest returns all but the first character of the string str in a string.

(rest "newLISP")           "ewLISP"
(first (rest "newLISP"))   "e"

関数 firstlast も見てください。
See also the first and last functions.

暗黙表現の rest がリストで使えることもお忘れなく。 restslice 的な暗黙インデックス の章を見てください。
Note that an implicit rest is available for lists. See the chapter Implicit rest and slice.

UTF-8 版 newLISP が使われている時、rest はバイト境界ではなく、キャラクタ境界で動作することに注意してください。
Note that rest works on character boundaries rather than byte boundaries when the UTF-8–enabled version of newLISP is used.



reverse !

syntax: (reverse list)
syntax: (reverse array)
syntax: (reverse string)

第一及び第二構文の reverse は、listarray を反転して返します。 reverse は破壊的であり、元のリストを変更しますので注意してください。
In the first and second form, reverse reverses and returns the list or array. Note that reverse is destructive and changes the original list or array.

; reverse a list
(set 'l '(a b c d e f))

(reverse l)   (f e d c b a)
l             (f e d c b a)
i
; reverse an array
(set 'a (array 3 2 '(1 2 3 4 5 6)))  ((1 2) (3 4) (5 6))

(reverse a)                          ((5 6) (3 4) (1 2))
a                                    ((5 6) (3 4) (1 2))

第三構文の reverse は、文字列の文字順を反転すために使います。
In the third form, reverse is used to reverse the order of characters in a string.

; reverse byte character string

(set 'str "newLISP")

(reverse str)   "PSILwen"
str             "PSILwen"

; reverse a multibyte character UTF-8 string, explode is UTF-8 sensitive

(join (reverse (explode "ΑΒΓΔΕΖΗΘ")))   "ΘΗΖΕΔΓΒΑ"

関数 sort も見てください。
See also the sort function.



rotate !

syntax: (rotate list [int-count])
syntax: (rotate str [int-count])

list や文字列 str を回転して返します。 オプションで一個より多い回転数を int-count に指定できます。 int-count が正なら、回転は右回りです。 int-count が負なら、回転は左回りです。 int-count が指定されない時、rotate は右に一個回転します。 rotate は、元のリストや文字列の内容を変える破壊的関数です。
Rotates and returns the list or string in str. A count can be optionally specified in int-count to rotate more than one position. If int-count is positive, the rotation is to the right; if int-count is negative, the rotation is to the left. If no int-count is specified, rotate rotates 1 to the right. rotate is a destructive function that changes the contents of the original list or string.

(set 'l '(1 2 3 4 5 6 7 8 9))

(rotate l)     (9 1 2 3 4 5 6 7 8)
(rotate l 2)   (7 8 9 1 2 3 4 5 6)

l   (7 8 9 1 2 3 4 5 6)

(rotate l -3)   (1 2 3 4 5 6 7 8 9)

; rotate a byte character string

(set 'str "newLISP")

(rotate str)      "PnewLIS"
(rotate str 3)    "LISPnew"
(rotate str -4)   "newLISP"

; rotate a multibyte character UTF-8 string on character boundaries

(join (rotate (explode "ΑΒΓΔΕΖΗΘ")))   "ΘΑΒΓΔΕΖΗ"

rotate が文字列に作用する時、文字境界ではなく、バイト境界で動作します。
When working on a string, rotate works on byte boundaries rather than character boundaries.



round

syntax: (round number [int-digits])

number の数値を与えられた int-digits の桁数で丸めます。 小数部を丸める時の int-digits は負数です。 整数部を丸める時は正数です。
Rounds the number in number to the number of digits given in int-digits. When decimals are being rounded, int-digits is negative. It is positive when the integer part of a number is being rounded.

この関数の int-digits が省略されると、小数部が 0 に丸められます。
If int-digits is omitted, the function rounds to 0 decimal digits.

(round 123.49 2)     100
(round 123.49 1)     120
(round 123.49 0)     123
(round 123.49)       123
(round 123.49 -1)    123.5
(round 123.49 -2)    123.49

表示目的で丸める時は、formatを使った方がより洗練されることに注意してください。
Note that rounding for display purposes is better accomplished using format.



save

syntax: (save str-file)
syntax: (save str-file sym-1 [sym-2 ... ])

第一構文の関数 save は、newLISP 作業領域の内容をファイル str-file に(テキスト形式で)書き込みます。 saveload の逆関数です。 save で作成したファイルを load することで、newLISP は save が実行された時と同じ状態に戻ります。 $ 文字で始まるシステム・シンボル (例えば、正規表現からの $0 やコマンド・ラインからの $main-args) や組込関数のシンボルや nil 等のシンボルは保存されません。
In the first syntax, the save function writes the contents of the newLISP workspace (in textual form) to the file str-file. save is the inverse function of load. Using load on files created with save causes newLISP to return to the same state as when save was originally invoked. System symbols starting with the $ character (e.g., $0 from regular expressions or $main-args from the command-line), symbols of built-in functions and symbols containing nil are not saved.

第二構文では、引数にシンボルを指定できます。 sym-n を提供すれば、そのシンボルの定義だけが保存されます。 sym-n がコンテキストに評価されるなら、そのコンテキスト内の全シンボルが保存されます。 一個以上のシンボルを指定でき、シンボルとコンテキスト・シンボルは混在可能です。 コンテキストが保存される時でも、システム変数や $ 文字で始まるシンボルは保存されません。 システム変数を指定した場合、それらは保存されます。
In the second syntax, symbols can be supplied as arguments. If sym-n is supplied, only the definition of that symbol is saved. If sym-n evaluates to a context, all symbols in that context are saved. More than one symbol can be specified, and symbols and context symbols can be mixed. When contexts are saved, system variables and symbols starting with the $ character are not saved. Specifying system symbols explicitly causes them to be saved.

各シンボルは set 宣言文で保存されます。 シンボルがラムダ関数かラムダ・マクロ関数なら、definedefine-macro 宣言文で保存されます。
Each symbol is saved by means of a set statement or—if the symbol contains a lambda or lambda-macro function—by means of define or define-macro statements.

save は、完了時に true を返します。
save returns true on completion.

(save "save.lsp")

(save "/home/myself/myfunc.LSP" 'my-func) 
(save "file:///home/myself/myfunc.LSP" 'my-func) 

(save "http://asite.com:8080//home/myself/myfunc.LSP" 'my-func)

(save "mycontext.lsp" 'mycontext) 

;; multiple args
(save "stuff.lsp" 'aContext 'myFunc '$main-args 'Acontext)

全てのコンテキスト・シンボルはコンテキスト MAIN の一部なので、MAIN の保存は全てのコンテキストを保存します。
Because all context symbols are part of the context MAIN, saving MAIN saves all contexts.

URL への保存は、URL へ送信するために HTTP PUT 要求リクエストを起こします。 このモードの save は、リモートの newLISP サーバー・ノードへプログラム・ソースをプッシュするために使えます。 パス名をルート・ディレクトリから相対的に指定する時は、二重のバックスラッシュが要求されることに注意してください。 HTTP モードの save は 60 秒でタイムアウトになります。
Saving to a URL will cause an HTTP PUT request to be sent to the URL. In this mode, save can also be used to push program source to remote newLISP server nodes. Note that a double backslash is required when path names are specified relative to the root directory. save in HTTP mode will observe a 60-second timeout.

sym を使って作られたシンボルは一般シンボルの構文ルールと互換性がないので、set 宣言文の代わりに sym を使って直列化シリアライズされます。
Symbols made using sym that are incompatible with the normal syntax rules for symbols are serialized using a sym statement instead of a set statement.

save がコンテキストとシンボルを直列化シリアライズする際、現在のコンテキストが MAIN であるかのように振る舞います。 つまり、現在のコンテキストに関わらず、save は常に同じ出力を生成します。
save serializes contexts and symbols as if the current context is MAIN. Regardless of the current context, save will always generate the same output.

save の逆操作である)関数 load とシンボルやコンテキストをファイルではなく文字列にする source も見てください。
See also the functions load (the inverse operation of save) and source, which saves symbols and contexts to a string instead of a file.



search

syntax: (search int-file str-search [bool-flag [regex-option]])

int-file のハンドルで指定されたファイルで str-search の文字列を検索します。 int-file は先行するファイルの open から得られます。 検索後、ファイル・ポインタは(訳注:bool-flag オプション次第で)検索文字列の最初か最後に位置し、見つからなかった時はファイルの最後です。
Searches a file specified by its handle in int-file for a string in str-search. int-file can be obtained from a previous open file. After the search, the file pointer is positioned at the beginning or the end of the searched string or at the end of the file if nothing is found.

デフォルトで、ファイルポインタは検索した文字列の最初に位置します。 bool-flagtrue に評価されると、ポインタは検索した文字列の最後に位置します。
By default, the file pointer is positioned at the beginning of the searched string. If bool-flag evaluates to true, then the file pointer is positioned at the end of the searched string.

regex-option に PCRE 正規表現検索のオプション・フラグを指定できます。 (訳注:正規表現オプション・フラグの)詳細は regex を見てください。 regex-option を指定しなければ、明快でより早い文字列検索が実行されます。 search は(訳注:見つかった時に)最新のファイル・ポインタを返し、見つからなかった時に nil を返します。
In regex-option, the options flags can be specified to perform a PCRE regular expression search. See the function regex for details. If regex-option is not specified a faster, plain string search is performed. search returns the new file position or nil if nothing is found.

正規表現オプション・フラグを使った時、見つかったパターンはシステム変数 $0$15 に保存されます。
When using the regular expression options flag, patterns found are stored in the system variables $0 to $15.

(set 'file (open "init.lsp" "read"))
(search file "define")
(print (read-line file) "\n")
(close file)

(set 'file (open "program.c" "r"))
(while (search file "#define (.*)" true 0) (println $1))
(close file)

ファイル init.lsp を開いて文字列 define を検索し、その文字列のある行を出力します。
The file init.lsp is opened and searched for the string define and the line in which the string occurs is printed.

二番目の例では、ファイル program.c 中に文字列 #define で始まる行を全て探し出し、文字列 "#define " 後の行の残りを出力します(訳注:bool-flagtrue であることに注意してください)。
The second example looks for all lines in the file program.c which start with the string #define and prints the rest of the line after the string "#define ".

正規表現を使った他の関数 directoryfindfind-allparseregexreplace を見てください。
For other functions using regular expressions, see directory, find, find-all, parse, regex, and replace.



seed

syntax: (seed int-seed)
syntax: (seed int-seed true [int-pre-N])
syntax: (seed)

ambnormalrandrandom 用に数値を発生する内部乱数発生器に、int-seed で指定された数値を種として与えます。 newLISP で使っている乱数発生器は C ライブラリ関数の rand() です。 newLISP の乱数関連関数は全て、この関数に基づいています。

Seeds the internal random generator that generates numbers for amb, normal, rand, and random with the number specified in int-seed. Note that the first syntax uses a random generator based on the C-library function rand(). All randomizing functions in newLISP are based on this function.

第二構文を使うと、全ての乱数発生を利用したか関数が newLISP を構築したブラットフォームに依存しない乱数発生器に基づくようになります。 第二構文で種を設定すると、ambnormalrandrandomrandomize から呼び出される全ての乱数関数は、このプラットフォーム非依存乱数発生器に基づきます。
When using the second syntax, all randomizing functions are based on a random generator independent of platforms and compilers used to built newLISP. When seeding with the second syntax all random functions called subsequently like amb, normal, rand, random and randomize are based on this platform independent random generator.

オプションの int-pre-N は、種を設定する初期化手続きでプリ・フェッチされる乱数の数を指定します。このパラメータを省略すると、seed50 を用います。
The optional int-pre-N specifies the number of random numbers to be pre- fetched as part of the seeding and initialization procedure. When this parameter is ommitted seed assumes 50.

int-seed の最大値は、使っているオペレーティング・システムによって 16 ビットか 32 ビットに制限されます。 内部的には、下位の 32 ビットが OS の乱数の種関数に渡されます。
Note that the maximum value for int-seed is limited to 16 or 32 bits, depending on the operating system used. Internally, only the 32 least significant bits are passed to the random seed function of the OS.

(seed 12345)

(seed (time-of-day))

同じ数値を seed に使った後、乱数発生器は同じ系列の数値で開始します。 これにより、乱数データにまつわるデバックが容易になります。 seed を使うことで、同じ乱数列を何度でも発生できるからです。
After using seed with the same number, the random generator starts the same sequence of numbers. This facilitates debugging when randomized data are involved. Using seed, the same random sequences can be generated over and over again.

二番目の例は、プログラム開始時間で異なる種を保証できるので重宝します。
The second example is useful for guaranteeing a different seed any time the program starts.

以下の例は、組込乱数発生器内部の種の状態の使われ方を示しています。
The following example shows usage of the internal seed state in the built-in random generator:

> (seed 123 true) ; use the true parameter
123
> (random)
0.2788576787704871
> (random)
0.7610070955758016
> (random)
0.2462553424976092
> (random)
0.8135413573186572
> (set 'state (seed)) ; save current state
1747066761
> (random)
0.1895924546707387
> (random)
0.4803856511043318
> (seed state true 0) ; seed with saved state
1747066761
> (random)            ; produces old sequence
0.1895924546707387       
> (random)
0.4803856511043318      
> 

最後の構文では、seed は現在の種の状態を返します。
In the last syntax seed returns the current seed state.



self

syntax: (self [int-index ... ])

関数 self は FOOP メソッドの目標オブジェクトにアクセスします。 オブジェクト・メンバーのアクセスに一個以上の int-index を使います。 self (訳注:でアクセスした要素)のセットには、演算子 : colon を使います。
The function self accesses the target object of a FOOP method. One or more int-index are used to access the object members. self is set by the : colon operator.

self で参照されるオブジェクトはミュータブルです:
Objects referenced with self are mutable:

(new Class 'Circle)

(define (Circle:move dx dy)
	(inc (self 1) dx) 
	(inc (self 2) dy))

(set 'aCircle (Circle 1 2 3))
(:move aCircle 10 20)

aCircle  (Circle 11 22 3)

; objects can be anonymous
(set 'circles '((Circle 1 2 3) (Circle 4 5 6)))

(:move (circles 0) 10 20)
(:move (circles 1) 10 20)

circles  ((Circle 11 22 3) (Circle 14 25 6))

FOOP プログラミングについては関数的オブジェクト指向プログラミングの章も見てください。
See also the chapter about programming with FOOP: Functional object-oriented programming



seek

syntax: (seek int-file [int-position])

int-file で指定されるファイルのファイル・ポインタを新しい位置 int-position に設定します。 新しい位置はファイルの先頭からのオプセットで表現され、0(ゼロ)がファイルの先頭を意味します。 int-position の指定がない時、seek はファイルの現在位置を返します。 BSD で int-file0(ゼロ)ならば、seek は STDOUT に出力した文字数を返します。Linux や MS Windows では -1 を返します。 失敗した時の seeknil を返します。 int-position-1 の時、seek はファイル・ポインタをファイルの最後に設定します。
Sets the file pointer to the new position int-position in the file specified by int-file.The new position is expressed as an offset from the beginning of the file, 0 (zero) meaning the beginning of the file. If no int-position is specified, seek returns the current position in the file. If int-file is 0 (zero), on BSD, seek will return the number of characters printed to STDOUT, and on Linux and MS Windows, it will return -1. On failure, seek returns nil. When int-position is set to -1, seek sets the file pointer to the end of the file.

seek はファイル位置を、現行ファイルの最後を越えて設定できます。 続けて、この位置に書き込むとファイルは拡張され、使われていない位置はゼロで埋められます。 このゼロのブロックはディスクに実際割り当てられないのでファイルは余計なスペースをとらず、スパースファイル と呼ばれます。(訳注:スパースファイルの関連記事
seek can set the file position past the current end of the file. Subsequent writing to this position will extend the file and fill unused positions with zero's. The blocks of zeros are not actually allocated on disk, so the file takes up less space and is called a sparse file.

(set 'file (open "myfile" "read"))   5 
(seek file 100)                      100
(seek file)                          100

(open "newlisp_manual.html" "read")
(seek file -1)  ; seek to EOF
 593816     

(set 'fle (open "large-file" "read") 
(seek file 30000000000)   30000000000

newLISP が提供するファイル位置数は 9,223,372,036,854,775,807 までです。
newLISP supports file position numbers up to 9,223,372,036,854,775,807.



select utf8

syntax: (select list list-selection)
syntax: (select list [int-index_i ... ])

syntax: (select string list-selection)
syntax: (select string [int-index_i ... ])

最初の二つの形式の selectは、list-selectionint-index_i で指定される一個以上のインデックスを使って、list から一個以上の要素を取り出します。
In the first two forms, select picks one or more elements from list using one or more indices specified in list-selection or the int-index_i.

(set 'lst '(a b c d e f g))

(select lst '(0 3 2 5 3))   (a d c f d)

(select lst '(-2 -1 0))   (f g a)

(select lst -2 -1 0)   (f g a)

次の二つの形式の select は、list-selectionint-index_i で指定される一個以上のインデックスを使って、string から一個以上の文字を取り出します。
In the second two forms, select picks one or more characters from string using one or more indices specified in list-selection or the int-index_i.

(set 'str "abcdefg") 

(select str '(0 3 2 5 3))   "adcfd"

(select str '(-2 -1 0))   "fga"

(select str -2 -1 0)   "fga"

選択する要素は何度でも使えます(訳注:つまり、重複するインデックスも可)。また、順番通りである必要はありませんが、(訳注:順番通りなら)動作は、速くなります。 list-selection または int-index_i の順序は、再編成される要素に合わせて変更できます。
Selected elements can be repeated and do not have to appear in order, although this speeds up processing. The order in list-selection or int-index_i can be changed to rearrange elements.





semaphore

syntax: (semaphore)
syntax: (semaphore int-id)
syntax: (semaphore int-id int-wait)
syntax: (semaphore int-id int-signal)
syntax: (semaphore int-id 0)

セマフォは内部プロセス同期用オブジェクトで、0(ゼロ)と最大値の間のカウントを維持します。 共有リソースへのアクセス制御用に使えるセマフォは、カウントがゼロより大きい時にシグナル状態に、カウントがゼロの時に非シグナル状態にセットされます。
A semaphore is an interprocess synchronization object that maintains a count between 0 (zero) and some maximum value. Useful in controlling access to a shared resource, a semaphore is set to signaled when its count is greater than zero and to non-signaled when its count is zero.

セマフォは、第一構文を使って生成されます。 これの際に返されるセマフォID は整数値で、次に関数 semaphore を呼び出す時の int-id として使えます。 最初のセマフォはゼロの値を持ち、非シグナル状態を表しています。
A semaphore is created using the first syntax. This returns the semaphore ID, an integer used subsequently as int-id when the semaphore function is called. Initially, the semaphore has a value of zero, which represents the non-signaled state.

int-wait に負数値を用いて semaphore を呼び出し、セマフォ値をゼロより下に減らそうとしても、他のプロセスが正数値の int-signal 用いてセマフォ値をシグナル状態にするまで、この関数呼び出しは 停止ブロックします。 int-signal を用いたセマフォの呼び出しは int-signal に指定された正数値によるセマフォ値の増加を試み、int-wait を用いたセマフォの呼び出しは int-wait に指定された負数値によるセマフォ値の減少を試みます。 セマフォは決してゼロより小さくはならないので、そうしようとしてもこの関数の呼び出しは 停止ブロックします (すなわち、ゼロのセマフォは、他のプロセスが int-signal を正の値に増加するまで 停止ブロックします) 。
If calling semaphore with a negative value in int-wait causes it to be decremented below zero, the function call will block until another process signals the semaphore with a positive value in int-signal. Calls to the semaphore with int-wait or int-signal effectively try to increment or decrement the semaphore value by a positive or negative value specified in int-signal or int-wait. Because the value of a semaphore must never fall below zero, the function call will block when this is attempted (i.e., a semaphore with a value of zero will block until another process increases the value with a positive int-signal).

第二構文はセマフォ値を要求するために使い、semaphoreint-id のみで呼び出します。 この形式は、MS Windows では利用できません。
The second syntax is used to inquire about the value of a semaphore by calling semaphore with the int-id only. This form is not available on MS Windows.

最後の引数に 0(ゼロ)を提供すれば、セマフォ用システム・リソースが解放され、利用できなくなります。 このセマフォにおける他の如何なる子プロセスの待ち状態も解放されます。
Supplying 0 (zero) as the last argument will release system resources for the semaphore, which then becomes unavailable. Any pending waits on this semaphore in other child processes will be released.

MS Windows では、親子関係のプロセスのみがセマフォを共有できます。 Linux/Unix では、プロセスに依存せずにセマフォを共有できます。
On MS Windows, only parent and child processes can share a semaphore. On Linux/Unix, independent processes can share a semaphore.

関数 semaphore は失敗すると nil を返します。 オペレーティングシステム下からエラー番号とそのテキストを取り出すために、sys-error が使えます。
On failure the semaphore function returns nil. sys-error can be used to retrieve the error number and text from the underlying operating system.

次のコード例は、異なる構文形式を要約しています:
The following code examples summarize the different syntax forms:

;; init semaphores 
(semaphore) 

;; assign a semaphore to sid 
(set 'sid (semaphore))

;; inquire the state of a semaphore (not on Windows OS)
(semaphore sid)

;; put sid semaphore in wait state (-1) 
(semaphore sid -1) 

;; run sid semaphore previously put in wait (always 1) 
(semaphore sid 1) 

;; run sid semaphore with X times a skip (backward or forward) on the function 
(semaphore sid X) 

;; release sid semaphore system-wide (always 0) 
(semaphore sid 0) 

次の例は、子プロセスを制御するセマフォを示しています:
The following example shows semaphores controlling a child process:

;; counter process output in bold

(define (counter n)
	(println "counter started")
	(dotimes (x n)
		(semaphore sid -1)
		(println x)))

;; hit extra <enter> to make the prompt come back
;; after output to the console from the counter process

> (set 'sid (semaphore))

> (semaphore sid)
0

> (fork (counter 100))

counter started
> (semaphore sid 1)
0
> (semaphore sid 3)
1
2
3
> (semaphore sid 2)
4

5
> _

セマフォが sid で獲得され、0 の値を持ちます(非シグナル状態)。 プロセス counter が始まると、初期開始メッセージを出した後、セマフォは停止ブロックし、セマフォ呼び出しの待ち状態になります。 -1 はセマフォ値を減らそうとしますが、既にゼロであり、できません。 メインの親プロセスのインターラクティブ環境でセマフォ値を 1 に上げて、シグナル状態にします。 これが counter プロセスのセマフォ呼び出しの待ちを解除し、それで(counterプロセスは)セマフォ値を 1 から 0 へと減らすことができ、print 宣言文が実行されます。 セマフォ呼び出しに再び到達すると、セマフォ値は既に待ち状態(0)になっているので停止ブロックします。
After the semaphore is acquired in sid, it has a value of 0 (the non-signaled state). When starting the process counter, the semaphore will block after the initial start message and will wait in the semaphore call. The -1 is trying to decrement the semaphore, which is not possible because its value is already zero. In the interactive, main parent process, the semaphore is signaled by raising its value by 1. This unblocks the semaphore call in the counter process, which can now decrement the semaphore from 1 to 0 and execute the print statement. When the semaphore call is reached again, it will block because the semaphore is already in the wait (0) state.

続く 1 より多い数での semaphore の呼び出しは、counter プロセスでセマフォが停止ブロックする前にセマフォ値を減らす機会を数回与えます。
Subsequent calls to semaphore with numbers greater than 1 give the counter process an opportunity to decrement the semaphore several times before blocking.

一個以上のセマフォの生成が可能なように、一個以上のプロセスがセマフォの制御に参加できます。 Unixライクのオペレーティングシステムでは、セマフォの最大数は kernel の system-wide 設定で制御されます。
More than one process can participate in controlling the semaphore, just as more than one semaphore can be created. The maximum number of semaphores is controlled by a system-wide kernel setting on Unix-like operating systems.

新プロセスの開始には関数 fork を、プロセス間の情報共有には関数 share を使ってください。 semaphore を使ったプロセス同期のより包括的な例は、newLISP で配布している例やモジュールと同様に配布ソースの examples ディレクトリ下にあるファイル prodcons.lsp を見てください。
Use the fork function to start a new process and the share function to share information between processes. For a more comprehensive example of using semaphore to synchronize processes, see the file prodcons.lsp example in the examples directory in the source distribution, as well as the examples and modules distributed with newLISP.



send

syntax: (send int-pid exp)
syntax: (send)

関数 send は、親プロセスと spawn で開始した子プロセス間の通信を可能にします。 親プロセスは子プロセスへメッセージを送り、子プロセスからのメッセージを受け取ることができます。 子プロセスも親プロセスへメッセージを送り、親プロセスからのメッセージを受け取ることができます。 後で示すようなプロキシ・テクニックは、子プロセス間同士の通信に使われます。 sendreceive は、ロックやセマフォを必要としません。 これらは、送信と受信、両方のメッセージ・キューで動作します。
The send function enables communication between parent and child processes started with spawn. Parent processes can send and receive messages to and from their child processes and child processes can send and receive messages to and from their parent process. A proxy technique – shown further down – is employed to communicate between child process peers. send and receive do not require locks or semaphores. They work on dual send and receive message queues.

forkprocess を使って開始したプロセスには、メッセージ関数 sendreceive を使えません。 代わりの通信用途としては、semaphore と一緒の sharepipe を使うべきです。
Processes started using fork or process can not use send and receive message functions. Instead they should use either share with semaphore or pipe to communicate.

関数 send は、MS Windows では使えません。
The send function is not available on MS Windows.

第一構文の send は親から子プロセスへ、あるいは子から親プロセスへのメッセージ送信に使われます。
In the first syntax send is used to send a message from a parent to a child process or a child to a parent process.

第二構文は親プロセスでのみ使われ、親からのメッセージを受信キューに受け入れ可能な子プロセスの全リストが得られます。 子プロセスの受信キューが満杯なら、(send) 宣言文で返るリストには含まれません。
The second syntax is only used by parent processes to get a list of all child processes ready to accept message from the parent in their receive queues. If a child's receive queue is full, it will not be part of the list returned by the (send) statement.

メッセージ内容は、アトム式、リスト式等の newLISP の如何なる式でもかまいません。例えば、niltrue からなる論理値、整数、浮動小数点数、文字列、newLISP 構文を含むリスト式等。 データの大きさに、制限はありません。
The content of a message may be any newLISP expression either atomic or list expressions: boolean constants nil and true, integers, floating point numbers or strings, or any list expression in valid newLISP syntax. The size of a message is unlimited.

exp パラメータには、int-pid の受け取り側に送るデータを指定します。 受け取り側は、現行プロセスが生成した子プロセスでも親プロセスでも可能です。 メッセージ・キューが満杯でも、最後に受信したものから読み取ることもできますが、 キューの反対側で実行された send は失敗し、nil を返します。
The exp parameter specifies the data to be sent to the recipient in int-pid. The recipient can be either a spawned child process of the current process or the parent process. If a message queue is full, it can be read from the receiving end, but a send issued on the other side of the queue will fail and return nil.

; child process dispatching message to parent

(set 'ppid (sys-info -4)) ; get parent pid

(send ppid "hello") ; send message

このメッセージの受け取り側目標は、親プロセスです:
The targeted recipient of the message is the parent process:

; parent process receiving message from child

(receive child-pid msg)  true
msg                      "hello"

send のキューが満杯の時は、メッセージ内容が受信側から十分に読み取られ、キューが send 宣言文から新しいメッセージを受け入れる準備ができるまで、 sendnil を返します。
When the send queue is full, send will return nil until enough message content is read on the receiving side of the queue and the queue is ready to accept new messages from send statements.

ループ関数 until を使えば、メッセージ宣言文は nil 以外の値を返すまで繰り返すことができます。 この方法で、ノン・ブロッキングな sendreceive を成功するまで止めておくことができます:
Using the until looping function, the message statements can be repeated until they return a value not nil. This way, non-blocking send and receive can be made blocking until they succeed:

; blocking sender
(until (send pid msg)) ; true after message is queued up

; blocking receiver
(until (receive pid msg)) ; true after message could be read

送り側の宣言文は、メッセージが受け取り側のメールボックスに届けられるまで止まっています。
The sender statement blocks until the message could be deposited in the recipients mailbox.

receive 宣言文は、新メッセージがキューから取り出されるまで止まっています。
The receive statement blocks until a new message can be fetched from the queue.

この例のように until 宣言文が本体式を欠いている時、評価された条件式の最後の値が until ループの戻り値になります。
As the until statements in this example lack body expressions, the last value of the evaluated conditional expression is the return value of the until loop.

Blocking message exchange(ブロッキング・メッセージ交換)

次のコードは、受け取り側が入力メッセージを待ち受け(listen)る方法を示し、同様に、送り側がキューへメッセージを送信するために再試行する方法を示しています。 例では、5 個の子プロセスが定期的に状態データを親プロセスに配信し、親プロセスでそのデータを表示する様子を示しています。 三組のデータが読み取られた後、親プロセスは全ての子プロセスを中止して、終了します:
The following code shows how a recipient can listen for incoming messages, and in turn how a sender can retry to deposit a message into a queue. The example shows 5 child processes constantly delivering status data to a parent process which will display the data. After three data sets have been read, the parent will abort all child processes and exit:

#!/usr/local/bin/newlisp

; child process transmits random numbers
(define (child-process)
    (set 'ppid (sys-info -4)) ; get parent pid
    (while true
        (until (send ppid (rand 100))))
)

; parent starts 5  child processes, listens and displays
; the true flag is specified to enable send/receive

(dotimes (i 5) (spawn 'result (child-process) true))

(for (i 1 3)
    (dolist (cpid (sync)) ; iterate thru child pids
        (until (receive cpid msg))
        (print "pid:" cpid "->" (format "%-2d  " msg)))
    (println)
)

(abort) ; cancel child-processes
(exit)

上の例を走らせると、次のような出力が作り出されます:
Running above example produces the following output:

pid:53181->47  pid:53180->61  pid:53179->75  pid:53178->39  pid:53177->3   
pid:53181->59  pid:53180->12  pid:53179->20  pid:53178->77  pid:53177->47  
pid:53181->6   pid:53180->56  pid:53179->96  pid:53178->78  pid:53177->18

(sync) は子プロセスの PID を全て返します。 各子プロセスからの状態メッセージを受け取とるまで待つために、(until (receive cpid msg)) を使っています。
The (sync) expression returns a list of all child PIDs, and (until (receive cpid msg)) is used to force a wait until status messages are received for each of the child processes.

ある時間経過後に待つのをやめるタイムアウト機能を、 until または while ループに含めることもできます。
A timeout mechanism could be part of an until or while loop to stop waiting after certain time has expired.

例では、子プロセスから親プロセスへと流れるメッセージを示すと共に、メッセージが親から子プロセスへと異なる方向へ流れることも示しています。 このような場合、メッセージ・キューの位置する子プロセスのリストを入手するために、親プロセスは (send) を使います。
The examples show messages flowing from a child processes to a parent process, in the same fashion messages could flow into the other direction from parent to child processes. In that case the parent process would use (send) to obtain a list of child processes with place in their message queues.

Messages containing code for evaluation(評価用コードを含むメッセージ)

メッセージ関数の最も強力な機能は、newLISP の式を送れることです。 そして、それを受け取り側で評価することができます。 受け取り側は、受け取った式の評価に eval 使います。 式に含まれるシンボルは受信側の環境で評価されます。
The most powerful feature of the message functions is the ability to send any newLISP expression, which then can be evaluated by the recipient. The recipient uses eval to evaluate the received expression. Symbols contained in the expression are evaluated in the receivers environment.

次の例は、親プロセスがメッセージ・プロキシのように振る舞う方法を示しています。 親プロセスは子プロセス A からメッセージを受け取り、ID B の第二子プロセスに発送します。 実際、これは子プロセス間のメッセージのやりとりを実現します。 この実装は、受け取り側が受け取ったメッセージに含まれる式を評価できるという事実に基づいています。 これらの式には、有効であれば如何なる newLISP 宣言文もかまいません:
The following example shows how a parent process acts like a message proxy. The parent receives messages from a child process A and routes them to a second child process with ID B. In effect this implements messages between child process peers. The implementation relies on the fact that the recipient can evaluate expressions contained in messages received. These expressions can be any valid newLISP statements:

#!/usr/local/bin/newlisp

; sender child process of the message
(set 'A (spawn 'result 
    (begin
        (dotimes (i 3)
            (set 'ppid (sys-info -4))
            /* the statement in msg will be evaluated in the proxy */
            (set 'msg '(until (send B (string "greetings from " A))))
            (until (send ppid msg)))
        (until (send ppid '(begin 
            (sleep 100) ; make sure all else is printed
            (println "parent exiting ...\n")
            (set 'finished true))))) true)) 

; receiver child process of the message
(set 'B (spawn 'result 
    (begin
        (set 'ppid (sys-info -4))
        (while true
            (until (receive ppid msg))
            (println msg)
            (unless (= msg (string "greetings from " A))
                (println "ERROR in proxy message: " msg)))) true))

(until finished (if (receive A msg) (eval msg))) ; proxy loop

(abort)
(exit)

子プロセス AB に 3個のメッセージを送ります。 これは直接できないので、A は評価してもらうため親プロセスに send 宣言文を送ります。宣言文:
Child process A sends three messages to B. As this cannot be done directly A sends send statements to the parent for evaluation. The statement:

(until (send pidB (string "greetings from " A)))

は、親プロセスの環境で評価されます。 変数 AB が送り側プロセス Anil に束縛されていたとしても、親プロセスでは正しい ID 番号に束縛されています。
will be evaluated in the environment of the parent process. Even so the variables A and B are bound to nil in the sender process A, in the parent process they will be bound to the correct process ID numbers.

三つのメッセージを送った後、宣言文:
After sending the three messages, the statement:

(set 'finished true)

は、親プロセスに送られます。一度だけ評価され、until ループを終了させます。
is sent to the parent process. Once evaluated, it will cause the until loop to finish.

sendreceive の更なる例題については Code Patterns 文書を見てください。
For more details on send and receive and more examples see the Code Patterns document.



sequence

syntax: (sequence num-start num-end [num-step])

num-start から num-end までの数列(訳注:等差数列)をオプション num-step のステップ・サイズで生成します。 num-step が省略された時は、値 1(一)になります。 生成される数値は(ステップ・サイズが指定されなかった時の)整数型か、(オプションのステップ・サイズがある時の)浮動小数点型です。
Generates a sequence of numbers from num-start to num-end with an optional step size of num-step. When num-step is omitted, the value 1 (one) is assumed. The generated numbers are of type integer (when no optional step size is specified) or floating point (when the optional step size is present).

(sequence 10 5)      (10 9 8 7 6 5)
(sequence 0 1 0.2)   (0 0.2 0.4 0.6 0.8 1)
(sequence 2 0 0.3)   (2 1.7 1.4 1.1 0.8 0.5 0.2)

高い数値から低い数値への数列でも、ステップ・サイズは正の数値でなければならないことに注意してください。
Note that the step size must be a positive number, even if sequencing from a higher to a lower number.

幾何数列(訳注:等比数列)の生成には、関数 series を使ってください。
Use the series function to generate geometric sequences.



series

syntax: (series num-start num-factor num-count)
syntax: (series exp-start func num-count)

第一構文の series は、要素 num-start から始まる要素 num-count 個の幾何数列(訳注:等比数列)を生成します。 一連の要素には num-factor が掛けられています。 生成される数値は、常に浮動小数点数です。
In the first syntax, series creates a geometric sequence with num-count elements starting with the element in num-start. Each subsequent element is multiplied by num-factor. The generated numbers are always floating point numbers.

num-count1 より小さい時、series は空リストを返します。
When num-count is less than 1, then series returns an empty list.

(series 2 2 5)      (2 4 8 16 32)
(series 1 1.2 6)    (1 1.2 1.44 1.728 2.0736 2.48832)
(series 10 0.9 4)   (10 9 8.1 7.29)
(series 0 0 10)     (0 0 0 0 0 0 0 0 0 0)
(series 99 1 5)     (99 99 99 99 99)

第二構文の series は、前の式から次の式に変わるために func で指定された関数を使います:
In the second syntax, series uses a function specified in func to transform the previous expression in to the next expression:

; embed the function Phi: f(x) = 1 / (1 + x)
; see also http://en.wikipedia.org/wiki/Golden_ratio

(series 1 (fn (x) (div (add 1 x))) 20)  

(1 0.5 0.6666666 0.6 0.625 0.6153846 0.619047 0.6176470 0.6181818 
 0.6179775 0.6180555 0.6180257 0.6180371 0.6180327 0.6180344 
 0.6180338 0.6180340 0.6180339 0.6180339 0.6180339)

; pre-define the function

(define (oscillate x) 
  (if (< x) 
    (+ (- x) 1) 
    (- (+ x 1)))
)

(series 1 oscillate 20)   

(1 -2 3 -4 5 -6 7 -8 9 -10 11 -12 13 -14 15 -16 17 -18 19 -20)

; any data type is accepted as a start expression

(series "a" (fn (c) (char (inc (char c)))) 5)  ("a" "b" "c" "d" "e")

; dependency of the two previous values in this fibonacci generator

(let (x 1) (series x (fn (y) (+ x (swap y x))) 10))  

(1 2 3 5 8 13 21 34 55 89)
 

最初の例は、(どんな値で始めても)黄金比、φに収束する数列を示しています。 二番目の例は、series 文を読み易くするため、前もって func を定義する方法を示しています。
The first example shows a series converging to the golden ratio, φ (for any starting value). The second example shows how func can be defined previously for better readability of the series statement.

関数 series は、内部リスト・インデックス値 $idx も更新しますので、func 内で使用することができます。
The series function also updates the internal list $idx index value, which can be used inside func.

算術数列(訳注:等差数列)には、関数 sequence を使ってください。
Use the sequence function to generate arithmetic sequences.



set !

syntax: (set sym-1 exp-1 [sym-2 exp-2 ... ])

両引数を評価し、exp の結果を sym で見つかるシンボルに割り当てます。 set 式は、割り当てた結果を返します。 割り当てられるのは、シンボルの右側の内容のコピーです。 シンボルの元の内容は、消去されます。 シンボル niltrue 若しくはコンテキスト・シンボルを変更しようとすると、結果はエラーメッセージとなります。 set は、複数の引数ペアを取ることができます。
Evaluates both arguments and then assigns the result of exp to the symbol found in sym. The set expression returns the result of the assignment. The assignment is performed by copying the contents of the right side into the symbol. The old contents of the symbol are deleted. An error message results when trying to change the contents of the symbols nil, true, or a context symbol. set can take multiple argument pairs.

(set 'x 123)      123
(set 'x 'y)       y
(set x "hello")   "hello"

y   "hello"

(set 'alist '(1 2 3))   (1 2 3)


(set 'x 1 'y "hello")   "hello"  ; multiple arguments

x   1
y   "hello"

割り当てられるシンボルは、別の newLISP 式からの結果でも可能です。 式は set 式中の変数に参照できます。
The symbol for assignment could be the result from another newLISP expression. Expressions can refer to variables in the set expression.

(set 'lst '(x y z))   (x y z)

(set (first lst) 123)   123

x   123

(set 'a 10 'b (+ a a))

a    10,  b    20

シンボルにラムダ式やラムダ・マクロ式をセットできます。 この操作は、 definedefine-macro の使用と等価です。
Symbols can be set to lambda or lambda-macro expressions. This operation is equivalent to using define or define-macro.

(set 'double (lambda (x) (+ x x)))
 (lambda (x) (+ x x))

は、以下と等価です:
is equivalent to:

(define (double x) (+ x x))
 (lambda (x) (+ x x))

次とも、等価です:
is equivalent to:

(define double (lambda (x) (+ x x)))
 (lambda (x) (+ x x))

シンボルをその後の変更から保護するには、(set のように作用する)関数 constant を使います。 関数 setqsetf を使えば、変数シンボルをクォートする必要がありません。
Use the constant function (which works like set) to protect the symbol from subsequent alteration. Using the setq or setf function eliminates the need to quote the variable symbol.



set-locale

syntax: (set-locale [str-locale [int-category]])

オペレーティングシステムやプラットフォームのロケールを報告したり、切り替えたりします。 引数なしで使う set-locale は、使われている現行ロケールを報告します。 str-locale が指定されている時の set-locale は、全てのカテゴリ・オプションがつけられている状態 (LC_ALL) でロケールを切り替えます。 str-locale に空文字列を置くと、現行プラットフォームで使っているデフォルトのロケールに切り替わります。
Reports or switches to a different locale on your operating system or platform. When used without arguments, set-locale reports the current locale being used. When str-locale is specified, set-locale switches to the locale with all category options turned on (LC_ALL). Placing an empty string in str-locale switches to the default locale used on the current platform.

set-locale は現行ロケールの文字列と小数点文字列のリストを返すか、要求された変更が実行できなかった時の nil を返します。
set-locale returns either the current locale string and decimal point string in a list or nil if the requested change could not be performed.

; report current locale

(set-locale)     

; set default locale of your platform and country
; return value shown when executing on German MS-Windows

(set-locale "")     ("German_Germany.1252" ",")
(add 1,234 1,234)   2,468

デフォルトの newLISP は – UTF-8 版でないなら – POSIX C デフォルト・ロケールで立ち上がります。 これにより、newLISPの振る舞いがプラットフォームのロケールによらず同一であることを保証します。UTF-8 版 newLISP では、現行プラットフォームのロケールが選択されます。
By default, newLISP – if not enabled for UTF-8 – starts up with the POSIX C default locale. This guarantees that newLISP's behavior will be identical on any platform locale. On UTF-8 enabled versions of newLISP the locale of the current platform is chosen.

; after non-UTF-8 newLISP start up

(set-locale)   ("C" ".")

int-categoryには、category options としての整数値を指定して、デイスプレイ数とか、日付表示とか等のロケールの一部を微調整します。 お使いのプラットフォームで有効なオプションは、C のインクルード・ファイル locale.h で見ることができ、プラットフォーム毎に異なっているかもしれません。 int-category を指定しなければ、LC_ALL オプションが使われ、そのロケールの全オプションが対象となります。
In int-category integer numbers may be specified as category options for fine-tuning certain aspects of the locale, such as number display, date display, and so forth. The options valid on your platform can be found in the C include file locale.h and may be different on each platform. When no int-category is specified, LC_ALL is used to turn on all options for that locale.

CategorymacOS, BSDs
& MS Windows
LC_ALL0
LC_COLLATE1
LC_CTYPE2
LC_MONETARY3
LC_NUMERIC4
LC_TIME5

デフォルトの C ロケールは小数点にドットを使いますが、カンマを使うものも他に数多く存在します。
The default C locale uses the decimal dot, but most others use a decimal comma.

; with the current locale "en_US.UTF-8", only change the decimal separator 
; to German locale comma on  macOS. LC_NUMERIC is 4 on most platforms 

(set-locale)  ("en_US.UTF-8" ".") 
(set-locale "de_DE.UTF-8" 4)  ("de_DE.UTF-8" ",") 

; mixed locale shows country setting for each category, 4 has changed
(set-locale)  ("en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/de_DE.UTF-8/en_US.UTF-8/en_US.UTF-8" ",")

set-locale を使っても、newLISPの正規表現の振る舞いは変わらないことに注意してください。 PCRE の振る舞いをローカライズするためには、newLISPを異なるキャラクタ・テーブルでコンパイルしなければなりません。 詳細は、newLISP 配布ソースのファイル LOCALIZATION を見てください。
Note that using set-locale does not change the behavior of regular expressions in newLISP. To localize the behavior of PCRE (Perl Compatible Regular Expressions), newLISP must be compiled with different character tables. See the file, LOCALIZATION, in the newLISP source distribution for details.

ロケールの切り替え の章も見てください。
See also the chapter Switching the locale.



set-ref !

syntax: (set-ref exp-key list exp-replacement [func-compare])

list 中で exp-key を検索し、見つかった要素を exp-replacement で置き換えます。 list は、入れ子のリストも使えます。 システム変数 $it には見つかった式が入り、exp-replacement で使うことができます。 この関数は、新たに変更された list を返します。
Searches for exp-key in list and replaces the found element with exp-replacement. The list can be nested. The system variables $it contains the expression found and can be used in exp-replacement. The function returns the new modified list.

(set 'data '(fruits (apples 123 44) (oranges 1 5 3)))

(set-ref 'apples data 'Apples)   (fruits (Apples 123 44) (oranges 1 5 3))

data  (fruits (Apples 123 44) (oranges 1 5 3)))

data にはデフォルト・ファンクションのコンテキスト指定子を使うことができ、この時のリストは参照で渡されます:
data could be the context identifier of a default function for passing lists by reference:

(set 'db:db '(fruits (apples 123 44) (oranges 1 5 3)))

(define (update ct key value)
	(set-ref key ct value))

(update db 'apples 'Apples)     (fruits (Apples 123 44) (oranges 1 5 3))
(update db 'oranges 'Oranges)   (fruits (Apples 123 44) (Oranges 1 5 3))

db:db  (fruits (Apples 123 44) (Oranges 1 5 3))

func-compare の使い方については、set-ref-all を見てください。
For examples on how to use func-compare see set-ref-all

リスト中に検出した全ての要素の変更には、set-ref-all を使ってください。
For changing all occurrences of an element in a list use set-ref-all.



set-ref-all !

syntax: (set-ref-all exp-key list exp-replacement [func-compare])

list 中で exp-key を検索し、見つかった要素を各々 exp-replacement で置き換えます。 list は、入れ子のリストも使えます。 システム変数 $it には見つかった要素が入り、exp-replacement で使えます。 システム変数 $count に、置換された数が入ります。 この関数は、新たに変更された list を返します。
Searches for exp-key in list and replaces each instance of the found element with exp-replacement. The list can be nested. The system variable $it contains the expression found and can be used in exp-replacement. The system variable $count contains the number of replacements made. The function returns the new modified list.

(set 'data '((monday (apples 20 30) (oranges 2 4 9)) (tuesday (apples 5) (oranges 32 1))))

(set-ref-all 'apples data "Apples")
  ((monday ("Apples" 20 30) (oranges 2 4 9)) (tuesday ("Apples" 5) (oranges 32 1)))

$count  2

(list key) パターンのデフォルト・ファンクタを使うことは、set-ref-all 宣言文を使ったユーザ定義関数にリストの参照渡しを許します。 これにより、大きなリストを扱う時のメモリ使用量を減らし高速化されます:
Using the default functor in the (list key) pattern allows the list to be passed by reference to a user-defined function containing a set-ref-all statement. This would result in less memory usage and higher speeds in when doing replacements in large lists:

(set 'db:db '((monday (apples 20 30) (oranges 2 4 9)) (tuesday (apples 5) (oranges 32 1))))

(define (foo ctx)
	(set-ref-all 'apples ctx "Apples")
)

(foo db) 
  ((monday ("Apples" 20 30) (oranges 2 4 9)) (tuesday ("Apples" 5) (oranges 32 1)))

(foo db) の評価の際、db:db のリストは参照で渡され、set-ref-alldb:db のコピーではなくオリジナルを変更します (訳注:newLISP のユーザ定義関数には、通常、引数が全てコピーで渡されます。上記手法の詳細は 参照によるデータの受け渡し を見てください)。
When evaluating (foo db), the list in db:db will be passed by reference and set-ref-all will make the changes on the original, not on a copy of db:db.

findreplacerefref-all のように、func-compare 中に matchunify を使えば、複雑な検索を表現できます:
Like with find, replace, ref and ref-all, complex searches can be expressed using match or unify in func-compare:

(set 'data '((monday (apples 20 30) (oranges 2 4 9)) (tuesday (apples 5) (oranges 32 1))))

(set-ref-all '(oranges *) data (list (first $it) (apply + (rest $it))) match)
     ( ... (oranges 15) ... (oranges 33) ... ) 

この例では、シンボル oranges で始まるレコードで見つかった全ての数値を合計しています。 見つかった要素は $it に現れます。
The example sums all numbers found in records starting with the symbol oranges. The found items appear in $it

見つかった最初の要素だけを置き換える set-ref も見てください。
See also set-ref which replaces only the first element found.



setq setf !

syntax: (setq place-1 exp-1 [place-2 exp-2 ... ])

newLISP の setqsetf は同じように動作し、シンボル・リスト・アレイ・文字列の中身、あるいはリスト・アレイ・文字列の参照位置の中身をセットします。 set のように、setqsetf は複数の引数ペアを取ることができます。 setqsetf の両方共、内部的には同じ組込関数を指していますが、このマニュアルでは setq がシンボル参照のセットに使われ、setf はリストやアレイの参照のセットに使われています。
setq and setf work alike in newLISP and set the contents of a symbol, list, array or string or of a list, array or string place reference. Like set, setq and setf can take multiple argument pairs. Although both setq and setf point to the same built-in function internally, throughout this manual setq is used when setting a symbol reference and setf is used when setting list or array references.

(setq x 123)   123

; multiple arguments

(setq x 1 y 2 z 3)   3 

x   1
y   2
z   3

; with nth or implicit indices
(setq L '(a b (c d) e f g))

(setf (L 1) 'B)       B
; or the same
(setf (nth 1 L) 'B)
L                     (a B (c d) e f g)

(setf (L 2 0) 'C)     C
L                     (a B (C d) e f g)

(setf (L 2) 'X)   
L                     (A B X e f g)

; with assoc
(setq L '((a 1) (b 2)))
(setf (assoc 'b L) '(b 3))  (b 3)
L                           ((a 1) (b 3))

; with lookup
(setf (lookup 'b L) 30)  30
L                        ((a 1) (b 30))

; several list accessors can be nested
(setq L '((a 1) (b 2)))

(push 'b (setf (assoc 'b l) '(b 4))) 'b)  b
L                                        ((a 1) (b b 4)))

; on strings
(set 's "NewISP")

(setf (s 0) "n")  "n"
s  "newISP"

(setf (s 3) "LI")  "LI"
s  "newLISP"

新しい値の設定が古い値に依存することは、有り勝ちです。 setf はアナフォリック・システム変数 $it を使って、setf 式内で古い値を参照できます:
Often the new value set is dependent on the old value. setf can use the anaphoric system variable $it to refer to the old value inside the setf expression:

(setq L '((apples 4) (oranges 1))) 

(setf (L 1 1) (+ $it 1))  2

L                         ((apples 4) (oranges 2))

(set 's "NewLISP")

(setf (s 0) (lower-case $it))  "n")

s  "newLISP"


sgn

syntax: (sgn num)
syntax: (sgn num exp-1 [exp-2 [exp-3]])

第一構文の関数 sgn は、次のルールに従って実数の符号を取り出す論理関数です:
In the first syntax, the sgn function is a logical function that extracts the sign of a real number according to the following rules:

x > 0 : sgn(x) = 1
x < 0 : sgn(x) = -1
x = 0 : sgn(x) = 0

(sgn -3.5)   -1
(sgn 0)      0
(sgn 123)    1

第二構文では、-1, 0, 1 の代わりに、オプション式 exp-1, exp-2, exp-3 の中の一つが評価されて返されます。 ケースに対応する exp-n が無い時は nil が返されます。
In the second syntax, the result of evaluating one of the optional expressions exp-1, exp-2, or exp-3 is returned, instead of -1, 0, or 1. If exp-n is missing for the case triggered, then nil is returned.

(sgn x -1 0 1)         ; works like (sgn x)
(sgn x -1 1 1)         ; -1 for negative x all others 1
(sgn x nil true true)  ; nil for negative else true
(sgn x (abs x) 0)      ; (abs x) for x < 0, 0 for x = 0, else nil

exp-1exp-2exp-3 には、如何なる式や定数も使えます。
Any expression or constant can be used for exp-1, exp-2, or exp-3.



share

syntax: (share)
syntax: (share int-address-or-handle)
syntax: (share int-address-or-handle exp-value)

syntax: (share nil int-address)

いくつかの newLISP プロセス間通信で共有するメモリをアクセスします。 引数なしで呼ばれた share は、オペレーティング・システムに共有メモリのページを要求します。 これにより、Linux/Unix ではメモリ・アドレスを、MS Windows ではハンドルを返すので、後で参照する変数に割り当てることができます。 この関数は OS/2 では利用できません。
Accesses shared memory for communicating between several newLISP processes. When called without arguments, share requests a page of shared memory from the operating system. This returns a memory address on Linux/Unix and a handle on MS Windows, which can then be assigned to a variable for later reference. This function is not available on OS/2.

共有メモリに内容をセットするには、share の第三構文を使います。 int-address-or-handle には Linux/Unix の共有メモリアドレスまたは MS Windows のハンドルを、exp-value には整数、浮動小数点、文字列式、その他の式( v.10.1.0から)を与えます。 この構文を使うと、値が exp-value に供給され、戻り値にもなります。
To set the contents of shared memory, use the third syntax of share. Supply a shared memory address on Linux/Unix or a handle on MS Windows in int-address-or-handle, along with an integer, float, string expression or any other expression (since v.10.1.0) supplied in exp-value. Using this syntax, the value supplied in exp-value is also the return value.

共有メモリの中身にアクセするには、共有メモリ・アドレスまたはハンドルのみを与える share の第二構文を使います。 戻り値は、先に書き込まれた如何なる定数や式にもなります( v.10.1.0から)。 値がセットされていなかった時は nil が返ります。
To access the contents of shared memory, use the second syntax of share, supplying only the shared memory address or handle. The return value will be any constant or expression (since v.10.1.0) written previously into the memory. If the memory has not been previously set to a value, nil will be returned.

最後の構文は Unixライクのオペレーティングシステムでのみ使用でき、共有メモリを解放します。 解放された後で、共有メモリを使うとシステムがクラッシュしますので注意してください。
Only available on Unix-like operating systems, the last syntax unmaps a shared memory address. Note that using a shared address after unmapping it will crash the system.

>メモリは独立したプロセス間ではなく、親子プロセス間で共有可能です。
Memory can be shared between parent and child processes, but not between independent processes.

10.1.0 から、共有オブジェクトの大きさはオペレーティング・システムのページサイズを超えることができます。 ページサイズより大きいオブジェクトでは、newLISP が内部でファイルを使って共有します。 この際、Unixライクのオペレーティング・システムでは /tmp ディレクトリを必要とします。 MS Windows システムでは、 環境変数 TEMP を用意しておくべきです。
Since 10.1.0 size of share objects can exceed the shared memory pagesize of the operating system. For objects bigger than the pagesize, newLISP internally uses files for sharing. This requires a /tmp directory on Unix-like operating system. On MS Windows systems the environment variable TEMP must be set.

(set 'mem (share))

(share mem 123)   123
(share mem)       123

(share mem "hello world")  "hello world"
(share mem)                "hello world"

(share mem true)   true
(share mem)        true

(share mem '(+ 1 2 3 4))   (+ 1 2 3 4)
(share mem)                (+ 1 2 3 4)

; expressions received can be evaluated (since v.10.1.0)
(eval (share mem))         10 

(share nil mem)    true  ; unmap only on Unix

共有メモリから読み出され評価される式は、読み出し側プロセスの環境下で評価されます。
Expression read from shared memory and evaluated, will be evaluated in the recipient's process environment.

異なるプロセス間の共有メモリ・アクセスは semaphore を使って、同期されるべきことに注意してください。 共有メモリの同時アクセスは、走っているプロセスをクラッシュしかねません。
Note that shared memory access between different processes should be synchronized using a semaphore. Simultaneous access to shared memory can crash the running process.

マルチ・プロセスの Linux/Unix アプリケーションで共有メモリを使ったより包括的な例は、newLISP 配布ソースのファイル example/prodcons.lsp で見てください。
For a more comprehensive example of using shared memory in a multi process Linux/Unix application, see the file example/prodcons.lsp in the newLISP source distribution.



signal

syntax: (signal int-signal sym-event-handler | func-event-handler)
syntax: (signal int-signal "ignore" | "default" | "reset")
syntax: (signal int-signal)

int-signal で指定されたシグナルに、sym-event-handler のユーザ定義関数または func-event-handler の関数式をセットします。
Sets a user-defined handler in sym-event-handler for a signal specified in int-signal or sets to a function expression in func-event-handler.

int-signal に続くオプション・パラメータは、評価されません。
A parameter following int-signal is not evaluated.

シグナルハンドラなしで指定される三つの文字列定数 "ignore""default""reset" は、いずれも小文字でも大文字でもよく、オプション文字列の第一文字だけでもかまいません。 三つのオプションのいずれかが指定されてセットアップが成功すると、true が返ります。
If no signal handler is specified any of the string constants "ignore", "default" or "reset" can be specified in either lower or upper case or simply using the first letter of the option string. When signal setup with any of these three options has been successful, true is returned.

"ignore" を使用すると、newLISP はシグナルを無視します。 "default" を使用すると、ハンドラはプラットフォーム下のデフォルト・ハンドラにセットされます。 "reset" オプションは、ハンドラをnewLISP 開始時の状態に戻します。
Using "ignore" will make newLISP ignore the signal. Using "default" will set the handler to the default handler of the underlying platform OS. The "reset" option will restore the handler to newLISP startup state.

newLISP は開始時に、空の newLISP ハンドラか、SIGINTSIGCHLD 用 C 呼び出し waitpipd(-1, 0, WNOHANG) である Ctrl-C ハンドラのどちらかを指定します。
On startup, newLISP either specifies an empty newLISP handler or a Ctrl-C handler for SIGINT and a waitpipd(-1, 0, WNOHANG) C-call for SIGCHLD.

異なる OS プラットフォームや Linux/Unix の類では、異なるシグナルが利用されます。 int-signal に指定する数値は、プラットフォーム毎に異なります。 有効な値は大抵、/usr/include/sys/signal.h/usr/include/signal.h から取り出せます。
Different signals are available on different OS platforms and Linux/Unix flavors. The numbers to specify in int-signal also differ from platform-to-platform. Valid values can normally be extracted from a file found in /usr/include/sys/signal.h or /usr/include/signal.h.

ユーザ定義ハンドラが指定されて実行していても、いくつかのシグナルは newLISP を終了させます(例えば、シグナル SIGKILL)。 この振る舞いは、プロットフォーム毎に異なります。
Some signals make newLISP exit even after a user-defined handler has been specified and executed (e.g., signal SIGKILL). This behavior may also be different on different platforms.

(constant 'SIGINT 2)
(define (ctrlC-handler) (println "ctrl-C has been pressed"))

(signal SIGINT 'ctrlC-handler)

; now press ctrl-C
; the following line will appear
; this will only work in an interactive terminal window

ctrl-C has been pressed

; reset treatment of signal 2 to startup conditions

(signal SIGINT "reset")

上記例だと、MS Windowsでは newLISP が終了する前にハンドラを実行します。 多くの Linux/Unix systemsでは newLISP がロードされたまま留まり、[enter] キーを打った後にプロンプトが現れます。
On MS Windows, the above example would execute the handler before exiting newLISP. On most Linux/Unix systems, newLISP would stay loaded and the prompt would appear after hitting the [enter] key.

シグナル・ハンドラが入ったシンボルを指定する代わりに、関数を直接指定できます。 (その際、)シグナル番号はパラメータとして渡せます:
Instead of specifying a symbol containing the signal handler, a function can be specified directly. The signal number is passed as a parameter:

(signal SIGINT exit)   $signal-2

(signal SIGINT (fn (s) (println "signal " s " occurred")))

シグナル SIGKILL (ほとんどのプラットフォームで 9 ) はシグナル・ハンドラの存在に関わらず、常にアプリケーションを終了させることに注意してください。
Note that the signal SIGKILL (9 on most platforms) will always terminate the application regardless of an existing signal handler.

シグナルは、同じコンピュータ上の別のシェルから送ることができます:
The signal could have been sent from another shell on the same computer:

kill -s SIGINT 2035

この例で、2035 は走っている newLISP のプロセス ID です。
In this example, 2035 is the process ID of the running newLISP.

シグナルは関数 destroy を使って別の newLISP アプリケーションから送ることもできます:
The signal could also have been sent from another newLISP application using the function destroy:

(destroy 2035)  true

newLISP が他の関数を評価中にシグナルを受け取ると、シグナルを受け入れ、ハンドラ関数を実行します:
If newLISP receives a signal while evaluating another function, it will still accept the signal and the handler function will be executed:

; only on Mac OSX, BSDs and Linux, not on Windows
(constant 'SIGINT 2)
(define (ctrlC-handler) (println "ctrl-C has been pressed"))

(signal SIGINT 'ctrlC-handler)
;; or
(signal SIGINT ctrlC-handler)


(while true (sleep 300) (println "busy"))

;; generates following output
busy
busy
busy
ctrl-C has been pressed
busy
busy
…

シグナル番号のみを指定すると、現在の定義ハンドラの名前か nil のどちらかが返ります。
Specifying only a signal number will return either the name of the currently defined handler function or nil.

ユーザ定義シグナル・ハンドラはパラメータにシグナル番号を渡せます。
The user-defined signal handler can pass the signal number as a parameter.

(define (signal-handler sig)
	(println "received signal: " sig))

;; set all signals from 1 to 8 to the same handler	
(for (s 1 8) 
	(signal s 'signal-handler))

この例では、1 から 8 までの全シグナルが同じハンドラにセットされます。
In this example, all signals from 1 to 8 are set to the same handler.



silent

syntax: (silent [exp-1 [exp-2 ... ]])

exp-1 以下の一個以上の式を評価します。 silentbegin に似ていますが、戻り値のコンソール出力とそれ続くプロンプトを抑制します。 これは、newLISPのリモート・アプリケーションからの通信(例えば、GUI フロント・エンドとか、他のnewLISP制御アプリケーションとか)の時や戻り値があまり意味のない時によく使われます
Evaluates one or more expressions in exp-1—. silent is similar to begin, but it suppresses console output of the return value and the following prompt. It is often used when communicating from a remote application with newLISP (e.g., GUI front-ends or other applications controlling newLISP), and the return value is of no interest.

プロンプトに戻ると、サイレント・モードは解除されます。 このため、式の一括処理時には引数なしで使うこともできます。 インターラクティブモードの時、silent 文を使った後でプロンプトに戻るには、[enter] を二度打ちます。
Silent mode is reset when returning to a prompt. This way, it can also be used without arguments in a batch of expressions. When in interactive mode, hit [enter] twice after a statement using silent to get the prompt back.

(silent (my-func))  ; same as next

(silent) (my-func)  ; same effect as previous


sin

syntax: (sin num-radians)

num-radians から正弦関数を計算し、結果を返します。
Calculates the sine function from num-radians and returns the result.

(sin 1)                      0.8414709838
(set 'pi (mul 2 (acos 0)))   3.141592654
(sin (div pi 2))             1


sinh

syntax: (sinh num-radians)

num-radians の双曲線正弦を計算します。 双曲線正弦は、次式で定義されています: (exp (x) - exp (-x)) / 2num-radians が大きすぎると、オーバーフローinf になります。
Calculates the hyperbolic sine of num-radians. The hyperbolic sine is defined mathematically as: (exp (x) - exp (-x)) / 2. An overflow to inf may occur if num-radians is too large.

(sinh 1)      1.175201194
(sinh 10)     11013.23287
(sinh 1000)   inf
(sub (tanh 1) (div (sinh 1) (cosh 1)))  0


sleep

syntax: (sleep num-milliseconds)

ミリ秒単位で指定された num-milli-seconds の CPU 時間を他のプロセスに与えます。
Gives up CPU time to other processes for the amount of milliseconds specified in num-milli-seconds.

(sleep 1000)  ; sleeps 1 second
(sleep 0.5)   ; sleeps 500 micro seconds

いくつかのプラットフォームでは、sleep は一秒の解像度でのみ利用できます。 この場合、int-milli-seconds パラメータは一番近い秒数に丸められます。
On some platforms, sleep is only available with a resolution of one second. In this case, the parameter int-milli-seconds will be rounded to the nearest full second.

sleepforkspawn で開始した子プロセスを終わらせるショート・カットになるでしょう。
A sleep may be cut short by a finishing child process started with fork or spawn.



slice

syntax: (slice list int-index [int-length])
syntax: (slice array int-index [int-length])
syntax: (slice str int-index [int-length])

第一形式の slice は、list から部分リスト(訳注:リストの一部)をコピーします。 元のリストは、変わりません。 部分リストはインデックス int-index から始まり、長さが int-length です。 int-length が負数なら、slice はパラメータを最後から数えるオフセットとして取りますが、そのオフセット位置は含みません(訳注:つまり、負数オフセット位置の要素は含まれない)。 (訳注:int-length)パラメータが無い場合、リストの最後までの全要素がコピーされます。)
In the first form, slice copies a sublist from a list. The original list is left unchanged. The sublist extracted starts at index int-index and has a length of int-length. If int-length is negative, slice will take the parameter as offset counting from the end and copy up to but not including that offset. If the parameter is omitted, slice copies all of the elements to the end of the list.

文字列、リスト、アレイの要素指定 も見てください。
See also Indexing elements of strings and lists.

(slice '(a b c d e f) 3 2)    (d e)
(slice '(a b c d e f) 2 -2)   (c d)
(slice '(a b c d e f) 2)      (c d e f)
(slice '(a b c d e f) -4 3)   (c d e)

(set 'A (array 3 2 (sequence 1 6)))  ((1 2) (3 4) (5 6))
(slice A 1 2)  ((3 4) (5 6))

第二形式では、文字列 str の一部を取り出します。 int-index には開始インデックス、int-length には部分文字列の長さが入ります。 int-length が指定されないと、文字列の終りまでの全てが取り出されます。 slice は、0(ゼロ)のようなバイナリ・データからなる文字列バッファでも動作します。 slice はキャラクタ境界ではなく、バイト境界で動作します。 文字列、リスト、アレイの要素指定 も見てください。
In the second form, a part of the string in str is extracted. int-index contains the start index and int-length contains the length of the substring. If int-length is not specified, everything to the end of the string is extracted. slice also works on string buffers containing binary data like 0's (zeroes). It operates on byte boundaries rather than character boundaries. See also Indexing elements of strings and lists.

UTF-8 版 newLISPでも、slice はオフセット数と長さにおいて、常に 8 ビット・1 バイト単位で動作することに注意してください。
Note that slice always works on single 8-bit byte boundaries for offset and length numbers, even when running the UTF-8 enabled version of newLISP.

(slice "Hello World" 6 2)   "Wo"
(slice "Hello World" 0 5)   "Hello"
(slice "Hello World" 6)     "World"
(slice "newLISP" -4 2)      "LI"

; UTF-8 strings are converted to a list, then joined again

(join (slice (explode "ΩΨΧΦΥΤΣΣΡΠΟΞΝΜΛΚΙΘΗΖΕΔΓΒΑ") 3 5))   "ΦΥΤΣΣ" 

implicit slice がリストでも使えることもお忘れなく。 restslice 的な暗黙インデックス を見てください。
Note that an implicit slice is available for lists. See the chapter Implicit rest and slice.

UTF-8版 newLISP でも、slice は常に文字境界ではなく、バイト境界で動作することを覚えておいてください。 そのため、slice はバイナリ・データの操作に使えます。
Be aware that slice always works on byte boundaries rather than character boundaries in the UTF-8–enabled version of newLISP. As a result, slice can be used to manipulate binary content.



sort !

syntax: (sort list [func-compare])
syntax: (sort array [func-compare])

listarray の全要素が、昇順に並べ替えられます。 型によらず、どんなものも並べ替えられます。 要素自身がリストの場合、各リスト要素は再帰的に比較されます。 異なる型の二つの式が比較されると、次の順序に従って低い型が高い型の前になります:
All members in list or array are sorted in ascending order. Anything may be sorted, regardless of the types. When members are themselves lists or arrays, each element is recursively compared. If two expressions of different types are compared, the lower type is sorted before the higher type in the following order:

Atoms: nil, true, integer or float, string, symbol, primitive
Lists: quoted expression, list, lambda, lambda-macro

sort は破壊的で、元のリストやアレイの要素の順序を変えて並べ替えたリストやアレイを返します。 安定したバイナリ・マージソートを使っているので、その性能は隣接した要素順でもほぼ O(n log2 n) が保たれます。 func-compare を使う時は、動作を安定させるために <=>= を一緒に使うべきです。
The sort is destructive, changing the order of the elements in the original list or array and returning the sorted list or array. It is a stable binary merge-sort with approximately O(n log2 n) performance preserving the order of adjacent elements which are equal. When func-compare is used it must work with either <= or >= operators to be stable.

オプションとして、比較演算子、ユーザ定義関数、無名関数を与えることができます。 ファンクタ(関数オブジェクト)やオペレータは、クォート無しで与えることが可能です。
An optional comparison operator, user-defined function, or anonymous function can be supplied. The functor or operator can be given with or without a preceding quote.

(sort '(v f r t h n m j))      (f h j m n r t v)
(sort '((3 4) (2 1) (1 10)))   ((1 10) (2 1) (3 4))
(sort '((3 4) "hi" 2.8 8 b))   (2.8 8 "hi" b (3 4))

(set 's '(k a l s))
(sort s)   (a k l s)  

(sort '(v f r t h n m j) >)  (v t r n m j h f)

(sort s <)   (a k l s)
(sort s >)   (s l k a)  
s            (s l k a)

;; define a comparison function
(define (comp x y) 
    (>= (last x) (last y)))
    
(set 'db '((a 3) (g 2) (c 5)))

(sort db comp)    ((c 5) (a 3) (g 2))

;; use an anonymous function
(sort db (fn (x y) (>= (last x) (last y))))


source

syntax: (source)
syntax: (source sym-1 [sym-2 ... ])

ほとんど save と同じように動作しますが、シンボルとコンテキストはファイルに書かれる代わりに、直列化シリアライズされます。 複数の変数シンボル、定義、コンテキストを指定できます。 引数が与えられない時、source は newLISP ワークスペースの全てを直列化シリアライズします。 同様に、コンテキストが文字列化される時、コンテキストに含まれるいかなるシンボルも直列化シリアライズされます。 nil の入っているシンボルは直列化シリアライズされません。 $ (dollar sign) 文字で始まるシステム変数は、指定された時のみ 直列化シリアライズされます。
Works almost identically to save, except symbols and contexts get serialized to a string instead of being written to a file. Multiple variable symbols, definitions, and contexts can be specified. If no argument is given, source serializes the entire newLISP workspace. When context symbols are serialized, any symbols contained within that context will be serialized, as well. Symbols containing nil are not serialized. System symbols beginning with the $ (dollar sign) character are only serialized when mentioned explicitly.

現在のコンテキストに従属しないシンボルは、それらのコンテキストが先付されて書き込まれます。
Symbols not belonging to the current context are written out with their context prefix.

(define (double x) (+ x x))

(source 'double)   "(define (double x)\n  (+ x x))\n\n"

save の時のように、関数 pretty-print を使って行分割や先導スペースやタブを制御することができます。
As with save, the formatting of line breaks and leading spaces or tabs can be controlled using the pretty-print function.



spawn

syntax: (spawn sym exp [true])

exp の評価を子プロセスとして起動し、すぐに戻ります。 sym はクォートされ、関数sync が実行された時の評価結果を受け取ります。 spawn は、コカレント・プロセスにおける式の並列評価開始に使われます。 マルチ・コア CPU 上で newLISP が走っているなら、オペレーティング・システム下で生成されたプロセスは別々のコアに割り当てられるでしょう。 その結果、式は並行して評価され、プロセス全体が高速化されます。
Launches the evaluation of exp as a child process and immediately returns. The symbol in sym is quoted and receives the result of the evaluation when the function sync is executed. spawn is used to start parallel evaluation of expressions in concurrent processes. If newLISP is running on a multi-core CPU, the underlying operating system will distribute spawned processes onto different cores, thereby evaluating expressions in parallel and speeding up overall processing.

生成した子プロセスとの通信に、sendreceive を使う時は、オプションの true パラメーターを設定しなければなりません。
The optional true parameter must be set if send or receive is used to communicated with the child process spawned.

関数spawn は MS Windows では使えません。
The function spawn is not available on MS Windows.

子プロセスを開始した後、spawn 式は分岐したプロセスのプロセス ID を返します。 次の例は、ある範囲の素数の計算において、範囲全体の計算の高速化を図るため、範囲を四つに分ける方法を示しています:
After successfully starting a child process, the spawn expression returns the process id of the forked process. The following examples shows how the calculation of a range of prime numbers can be split up in four sub ranges to speed up the calculation of the whole range:

; calculate primes in a range
(define (primes from to)
  (local (plist)
      (for (i from to)
          (if (= 1 (length (factor i)))
              (push i plist -1)))
      plist))

; start child processes
(set 'start (time-of-day))

(spawn 'p1 (primes 1 1000000))
(spawn 'p2 (primes 1000001 2000000))
(spawn 'p3 (primes 2000001 3000000))
(spawn 'p4 (primes 3000001 4000000))

; wait for a maximum of 60 seconds for all tasks to finish
(sync 60000) ; returns true if all finished in time
; p1, p2, p3 and p4 now each contain a lists of primes

(println "time spawn: " (- (time-of-day) start))
(println "time simple: " (time  (primes 1 4000000)))

(exit)

1.83 Intel Core 2 Duo processor 上で、上記例は約 13 秒で終了します。 (primes 1 4000000) を使った素数の計算は、およそ20秒かかります。
On a 1.83 Intel Core 2 Duo processor, the above example will finish after about 13 seconds. Calculating all primes using (primes 1 4000000) would take about 20 seconds.

関数 sync は全ての子プロセスが終了するまで待ち、評価結果をシンボル p1p4 で受け取ります。 全ての結果が集まると、sync は待つのを止めて true を返します。 指定された時間が不足している時、syncnil を返しますが、別の sync 宣言文に十分なウェイトを与えて結果を集めることができます。 短いタイムアウトを使って、待っている間に他のプロセスを行えます:
The sync function will wait for all child processes to finish and receive the evaluation results in the symbols p1 to p4. When all results are collected, sync will stop waiting and return true. When the time specified was insufficient , sync will return nil and another sync statement could be given to further wait and collect results. A short timeout time can be used to do other processing during waiting:

(spawn 'p1 (primes 1 1000000))
(spawn 'p2 (primes 1000001 2000000))
(spawn 'p3 (primes 2000001 3000000))
(spawn 'p4 (primes 3000001 4000000))

; print a dot after each 2 seconds of waiting
(until (sync 2000) (println "."))

パラメータ無しで使われた sync は待たずに、すぐにペンディング中の子プロセスのリストを返します。 primes の例では、続く sync 式が進行状態を見るために使われています:
sync when used without any parameters, will not wait but immediately return a list of pending child processes. For the primes example, the following sync expression could be used to watch the progress:

(spawn 'p1 (primes 1 1000000))
(spawn 'p2 (primes 1000001 2000000))
(spawn 'p3 (primes 2000001 3000000))
(spawn 'p4 (primes 3000001 4000000))

; show a list of pending process ids after each three-tenths of a second
(until (sync 300) (println (sync)))

-1 のパラメータは、sync に非常に長い時間 (~ 1193 時間) を指定します。 より良い解決法は、待てるだけ待ってから、全てのペンディング中の子プロセスを abort することです:
A parameter of -1 tells sync to wait for a very long time (~ 1193 hours). A better solution would be to wait for a maximum time, then abort all pending child processes:

(spawn 'p1 (primes 1 1000000))
(spawn 'p2 (primes 1000001 2000000))
(spawn 'p3 (primes 2000001 3000000))
(spawn 'p4 (primes 3000001 4000000))

; wait for one minute, then abort and
; report unfinished PIDs

(if (not (sync 60000))
    (begin
        (println "aborting unfinished: " (sync))
        (abort))
    (println "all finished successfully")
)

spawnsyncabort の三関数は、Cilk API 部品です。 オリジナルの実装は、マルチ CPU コア用に細分されたタスクの洗練されたスケジュール管理と割り当てを実行します。 newLISP の Cilk API 実装は、プラットフォーム下のオペレーティングシステムにプロセス管理を扱わせます。 API の中身は、Unix libc 関数 fork()waitpid()kill() を使って実装されています。 プロセスと子プロセス間の内部通信は、関数 sendreceive を使って実行されます。
The three functions spawn, sync and abort are part of the Cilk API. The original implementation also does sophisticated scheduling and allocation of threaded tasks to multiple CPU cores. The newLISP implementation of the Cilk API lets the operating system of the underlying platform handle process management. Internally, the API is implemented using the Unix libc functions fork(), waitpid() and kill(). Intercommunications between processes and child processes is done using the send and receive functions.

spawn を生成されたサブタスクから再帰的に呼び出すこともできます:
spawn can be called recursively from spawned subtasks:

(define (fibo n)
  (local (f1 f2)
    (if(< n 2) 1
       (begin
          (spawn 'f1 (fibo (- n 1)))
          (spawn 'f2 (fibo (- n 2)))
          (sync 10000)
          (+ f1 f2)))))

(fibo 7)   21

(fibo 7) では、41 プロセスが生成されます。 上記コードは、再帰アプリケーション での Cilk API の動作を示していますが、spawn のサブタスクに要求されるオーバーヘッドが並列化で救われる時間よりもはるかに大きいので、実用的ではありません。
With (fibo 7) 41 processes will be generated. Although the above code shows the working of the Cilk API in a recursive application, it would not be practical, as the overhead required to spawn subtasks is much higher than the time saved through parallelization.

バージョン 10.1 以来、メッセージ関数 sendreceive は、親子のプロセス間通信に利用できます。 これらの関数を使うことで、いかなるサイズのいかなるデータや式も伝送できます。 付け加えて、メッセージの式は受け取り側の環境で評価されます。
Since version 10.1 a send and receive message functions are available for communications between parent and child processes. Using these functions any data or expression of any size can be transferred. Additionally messaged expressions can be evaluated in the recipient's environment.

newLISP プロセスを開始する別の方法として、forkprocess があります。
fork and process are other functions to start newLISP processes.



sqrt

syntax: (sqrt num)

num の式から平方根を計算し、結果を返します。
Calculates the square root from the expression in num and returns the result.

(sqrt 10)   3.16227766
(sqrt 25)   5


ssq

syntax: (ssq list-vector | array-vector)

list-vectorarray-vector ベクトル中の数値の二乗和を計算します。
Calculates the sum of squares of numbers in a vector in list-vector or array-vector.

(set 'vector (sequence 1 10))
(ssq vector)  385

(set 'vector (array 10 (sequence 1 10)))
(ssq vector)  385


starts-with

syntax: (starts-with str str-key [num-option])
syntax: (starts-with list [exp])

第一形式の starts-with は、文字列 str がキー文字列 str-key から始まるかどうかをチェックし、結果次第で truenil を返します。
In the first version, starts-with checks if the string str starts with a key string in str-key and returns true or nil depending on the outcome.

正規表現用の数値を num-option に指定するなら、str-key に入るのは正規表現パターンです。 有効な option 番号は regex を参照してください。
If a regular expression number is specified in num-option, str-key contains a regular expression pattern. See regex for valid option numbers.

(starts-with "this is useful" "this")         true
(starts-with "this is useful" "THIS")         nil

;; use regular expressions
(starts-with "this is useful" "THIS" 1)       true
(starts-with "this is useful" "this|that" 0)  true

第二形式の starts-with は、リストが exp のリスト要素で始まるかどうかをチェックし、結果次第で truenil を返します。
In the second version, starts-with checks to see if a list starts with the list element in exp. true or nil is returned depending on outcome.

(starts-with '(1 2 3 4 5) 1)              true
(starts-with '(a b c d e) 'b)             nil
(starts-with '((+ 3 4) b c d) '(+ 3 4))   true

関数 ends-with も見てください。
See also the ends-with function.



stats

syntax: (stats list-vector)

この関数は list-vector の値から、中心傾向分布積率などの様々な統計値を計算します。 stats が返すリストには次の値が入ります:
The functions calculates statistical values of central tendency and distribution moments of values in list-vector. The following values are returned by stats in a list:

namedescription
N個数
Number of values
mean平均値
Mean of values
avdev平均偏差
Average deviation from mean value
sdev標準偏差(母集団推定)
Standard deviation (population estimate)
var分散(母集団推定)
Variance (population estimate)
skew分布の歪度
Skew of distribution
kurt分布の尖度
Kurtosis of distribution

次の例は stats の出力リスト式を format 宣言文の引数に使っています:
The following example uses the list output from the stats expression as an argument for the format statement:

(set 'data '(90 100 130 150 180 200 220 300 350 400))

(println (format [text]
    N        = %5d
    mean     = %8.2f
    avdev    = %8.2f
    sdev     = %8.2f
    var      = %8.2f
    skew     = %8.2f
    kurtosis = %8.2f
[/text] (stats data)))

; outputs the following

    N        =    10
    mean     =   212.00
    avdev    =    84.40
    sdev     =   106.12
    var      = 11262.22
    skew     =     0.49
    kurtosis =    -1.34



string

syntax: (string exp-1 [exp-2 ... ])

exp-1– の評価のいかなる結果も、文字列に変換します。 一個の式より多い場合、結果の文字列は結合されます。
Translates into a string anything that results from evaluating exp-1—. If more than one expression is specified, the resulting strings are concatenated.

(string 'hello)           "hello"
(string 1234)             "1234"
(string '(+ 3 4))         "(+ 3 4)"
(string (+ 3 4) 8)        "78"
(string 'hello " " 123)   "hello 123"

string に渡されたバッファが \000 を含んでいるなら、最初のゼロ(訳注:\000)までの文字列がコピーされます:
If a buffer passed to string contains \000, only the string up to the first terminating zero will be copied:

(set 'buff "ABC\000\000\000")   "ABC\000\000\000"

(length buff)   6

(string buff)   "ABC"

(length (string buff))   3

ゼロ・バイトを含む文字列の結合には、関数 append か(指定された結合文字を許可する)join を使ってください。 ラムダ式を newLISP ソース文字列表現に変換するためには、関数 source を使ってください。
Use the append and join (allows the joining string to be specified) functions to concatenate strings containing zero bytes. Use the source function to convert a lambda expression into its newLISP source string representation.



string?

syntax: (string? exp)

exp を評価し、それが文字列かどうかをテストします。 結果次第で truenil が返ります。
Evaluates exp and tests to see if it is a string. Returns true or nil depending on the result.

(set 'var "hello")
(string? var)   true


struct

syntax: (struct symbol [str-data-type ... ])

関数 structlibffi をコンパイルした newLISP 全バージョンで利用可能で、importpackunpack の拡張構文で使用するデータ型集合体を定義するために使えます。これにより、C 言語の構造体 データ型やデータ型集合体のポインタを取る関数の導入が可能になります。
The struct function can be used to define aggregate data types for usage with the extended syntax of import, pack and unpack, available on all versions of newLISP compiled with libffi. This allows importing functions which take C-language struct data types or pointers to these aggregate data types.

以下の例では、C のデータ関数 localtimeasctime における struct の使い方を示しています。 関数 localtime は組込関数 now に似た動作をします。 関数 asctimelocaltime の出力する数値データを取って、可読性のよいテキストに整形します。
The following example illustrates the usage of struct together with the C data functions localtime and asctime. The localtime functions works similar to the built-in now function. The asctime function takes the numerical data output by localtime and formats these to readable text.

/* The C function prototypes for the functions to import */

struct tm * localtime(const time_t *clock);

char * asctime(const struct tm *timeptr);

/* the tm struct aggregating different time related values */

struct tm {
    int tm_sec;      /* seconds after the minute [0-60] */
    int tm_min;      /* minutes after the hour [0-59] */
    int tm_hour;     /* hours since midnight [0-23] */
    int tm_mday;     /* day of the month [1-31] */
    int tm_mon;      /* months since January [0-11] */
    int tm_year;     /* years since 1900 */
    int tm_wday;     /* days since Sunday [0-6] */
    int tm_yday;     /* days since January 1 [0-365] */
    int tm_isdst;    /* Daylight Savings Time flag */
    long tm_gmtoff;  /* offset from CUT in seconds */   /*** not on Windows ***/
    char *tm_zone;   /* timezone abbreviation */        /*** not on Windows ***/
};

newLISP における関数の導入と構造体データ型の定義:
Function import and definition of the structure data type in newLISP:

;; for pointers to structs always use void*
;; as a library use msvcrt.dll on Windows or libc.so on Unix.
;; The tm struct type is configured for Mac OSX and Linux.
;; On other OS the tm structure may be different
 
(import "libc.dylib" "asctime" "char*" "void*")
(import "libc.dylib" "localtime" "void*" "void*")

; definition of the struct
(struct 'tm "int" "int" "int" "int" "int" "int" "int" "int" "int" "long" "char*")


;; use import and struct

; todays date number (seconds after 1970 also called Unix epoch time)
(set 'today (date-value))   1324134913

;; the time value is passed by it's address
;; localtime retirns a pointer to a tm struct

(set 'ptr (localtime (address today)))  2896219696

; unpack the tm struct  (7:15:13 on the 17th etc.)
(unpack tm ptr)  (13 15 7 17 11 111 6 350 0 -28800 "PST")

; transform to readable form
(asctime ptr)  "Sat Dec 17 07:15:13 2011\n"

; all in one statement does actually not use struct, pointers are passed directly
(asctime (localtime (address today)))  "Sat Dec 17 07:15:13 2011"

; same as the built-in date function
(date today)  "Sat Dec 17 07:15:13 2011"

導入された関数へのポインタ変数には有効なアドレスを渡すように注意すべきです。 unpack にアドレス・ポインタを渡す際も同様です。 無効なアドレス・ポインタは newLISP をクラッシュしたり、動作を不安定にしかねません。
Care must be taken to pass valid addresses to pointer parameters in imported functions or when passing address pointers to unpack. Invalid address pointers can crash newLISP or make it unstable.

struct の定義は入れ子も可能です:
struct definitions can be nested:

; the pair aggregate type
(struct 'pair "char" "char")  pair

; nested struct type
(struct 'comp "pair" "int")   comp

; pack data using the extended pack syntax
; note the insertion of structure alignment bytes after the pair
(pack comp (pack pair 1 2) 3)  "\001\002\000\000\003\000\000\000"

; unpack reverses the process
(unpack comp "\001\002\000\000\003\000\000\000")  ((1 2) 3)

入れ子構造は再帰的にアンパックされます。
Nested structures are unpacked recursively.



sub

syntax: (sub num-1 [num-2 ... ])

num-1, num-2 以下の式を連続的に引き算します。 sub は(訳注:整数と浮動小数点数の)混在型算術を実行し、整数と浮動小数点を扱えますが、常に浮動小数点を返します。 一個だけの引数が供給された時は、符号が逆になります。 NaN を伴なう浮動小数点計算では如何なる場合も NaN を返します。
Successively subtracts the expressions in num-1, num-2—. sub performs mixed-type arithmetic and handles integers or floating points, but it will always return a floating point number. If only one argument is supplied, its sign is reversed. Any floating point calculation with NaN also returns NaN.

(sub 10 8 0.25)   1.75
(sub 123)         -123


swap !

syntax: (swap place-1 place-2)

place-1 と place-2 の内容を交換します。 place の対象となるのは、クォートなしのシンボル、リスト、nthfirstlast で表れされた参照、暗黙の 要素指定assoclookup で参照された場所等の中身です。
The contents of the two places place-1 and place-2 are swapped. A place can be the contents of an unquoted symbol or any list or array references expressed with nth, first, last or implicit indexing or places referenced by assoc or lookup.

swap は含まれているリスト、アレイ、シンボルを変化させる破壊的操作です。
swap is a destructive operation that changes the contents of the lists, arrays, or symbols involved.

(set 'lst '(a b c d e f))

(swap (first lst) (last lst))  a
lst                            (f b c d e a)

(set 'lst-b '(x y z))

(swap (lst 0) (lst-b -1))  f
lst                        (z b c d e a)
lst-b                      (x y f)

(set 'A (array 2 3 (sequence 1 6))  ((1 2 3) (4 5 6))

(swap (A 0) (A 1))  (1 2 3)
A                   ((4 5 6) (1 2 3))

(set 'x 1 'y 2)

(swap x y)   1
x   2
y   1

(set 'lst '((a 1 2 3) (b 10 20 30)))
(swap (lookup 'a lst -1) (lookup 'b lst 1))
lst  ((a 1 2 10) (b 3 20 30))

(swap (assoc 'a lst) (assoc 'b lst))
lst   ((b 3 20 30) (a 1 2 10))

二つの場所が如何なるものであれ、同じまたは違うオブジェクトが交換されます。
Any two places can be swept in the same or different objects.



sym

syntax: (sym string [sym-context [nil-flag]])
syntax: (sym number [sym-context [nil-flag]])
syntax: (sym symbol [sym-context [nil-flag]])

第一引数の stringnumbersymbol をシンボルに変換し、それを返します。 sym-context にコンテキストが指定されない時は、シンボルを参照した時、または生成する時の現コンテキストが使われます。 シンボルが存在していない時は生成されます。 存在していないコンテキストがクォート付きシンボルで指定された時も、シンボルは生成されます(訳注:コンテキストも生成されます)。 コンテキスト指定がクォート無しの時、コンテキストが指定された名前になるか、コンテキスト指定がそのコンテキストを含む変数になります(訳注:この場合、コンテキストが存在していないと、エラーになります)。
Translates the first argument in string, number, or symbol into a symbol and returns it. If the optional context is not specified in sym-context, the current context is used when doing symbol lookup or creation. Symbols will be created if they do not already exist. When the context does not exist and the context is specified by a quoted symbol, the symbol also gets created. If the context specification is unquoted, the context is the specified name or the context specification is a variable containing the context.

sym は、newLISP ソース・コードでは適正でないシンボルをシンボル・テーブル内に生成できます(例えば、数字、括弧やコロン等の特殊文字を含む名前) 。 これにより、他のスクリプト言語における hash table アクセスのような連想メモリ・アクセス用の関数として、sym を使えるようになります。
sym can create symbols within the symbol table that are not legal symbols in newLISP source code (e.g., numbers or names containing special characters such as parentheses, colons, etc.). This makes sym usable as a function for associative memory access, much like hash table access in other scripting languages.

第三引数オプションとして、シンボルが見つからない時のシンボル生成を止めるために、nil を指定できます。 この場合、シンボルが存在しない時の symnil を返します。 この最後の形式を使うことで、sym をシンボルの存在チェックに使えます。
As a third optional argument, nil can be specified to suppress symbol creation if the symbol is not found. In this case, sym returns nil if the symbol looked up does not exist. Using this last form, sym can be used to check for the existence of a symbol.

(sym "some")            some
(set (sym "var") 345)   345
var                     345
(sym "aSym" 'MyCTX)     MyCTX:aSym
(sym "aSym" MyCTX)      MyCTX:aSym  ; unquoted context

(sym "foo" MyCTX nil)   nil  ; 'foo does not exist
(sym "foo" MyCTX)       foo  ; 'foo is created
(sym "foo" MyCTX nil)   foo  ; foo now exists

関数 sym はシンボルを検出または生成するので、sym と一緒の式はシンボルを引数として使う他の式に直接埋め込めます。 次の例では、連想メモリ・アクセスのハッシュ・ライク関数としての sym の使用例と、同時に newLISP シンボルとして適正でないシンボルの生成を示しています:
Because the function sym returns the symbol looked up or created, expressions with sym can be embedded directly in other expressions that use symbols as arguments. The following example shows the use of sym as a hash-like function for associative memory access, as well as symbol configurations that are not legal newLISP symbols:

;; using sym for simulating hash tables

(set (sym "John Doe" 'MyDB) 1.234)
(set (sym "(" 'MyDB) "parenthesis open")
(set (sym 12 'MyDB) "twelve")

(eval (sym "John Doe" 'MyDB))   1.234
(eval (sym "(" 'MyDB))          "parenthesis open"
(eval (sym 12 'MyDB))           "twelve"

;; delete a symbol from a symbol table or hash
(delete (sym "John Doe" 'MyDB))   true

最後の行は、delete を使ってシンボルを削除できる例です。
The last statement shows how a symbol can be eliminated using delete.

第三構文は、シンボル名としての文字列の代わりに、シンボルを目標コンテキストに使われることを許します。 この場合、sym はシンボルから名前を取り出し、それを目標コンテキストでのシンボル用名前の文字列として使います:
The third syntax allows symbols to be used instead of strings for the symbol name in the target context. In this case, sym will extract the name from the symbol and use it as the name string for the symbol in the target context:

(sym 'myVar 'FOO)   FOO:myVar

(define-macro (def-context)
  (dolist (s (rest (args)))
    (sym s (first (args)))))

(def-context foo x y z)

(symbols foo)   (foo:x foo:y foo:z)

def-context マクロは、これ(訳注:sym)が動的にコンテキストとその変数を生成するマクロを生成するために、どのように使われているかを示しています。
The def-context macro shows how this could be used to create a macro that creates contexts and their variables in a dynamic fashion.

関数 context の構文は、シンボルの生成、セット、評価にも使えます。
A syntax of the context function can also be used to create, set and evaluate symbols.



symbol?

syntax: (symbol? exp)

exp を評価し、その値がシンボルなら true を返し、それ以外では nil を返します。
Evaluates the exp expression and returns true if the value is a symbol; otherwise, it returns nil.

(set 'x 'y)   y

(symbol? x)   true 

(symbol? 123)   nil

(symbol? (first '(var x y z)))   true

一行目は、x の内容をシンボル y にセットしています。 二行目は、x の内容をチェックしています。 最後の例は、リストの最初の要素をチェックしています。
The first statement sets the contents of x to the symbol y. The second statement then checks the contents of x. The last example checks the first element of a list.



symbols

syntax: (symbols [context])

引数なしで呼ばれた時、現コンテキストでの全シンボルのリストをソートして返します。 コンテキスト・シンボルを指定すると、そのコンテキストで定義されたシンボルを返します。
Returns a sorted list of all symbols in the current context when called without an argument. If a context symbol is specified, symbols defined in that context are returned.

(symbols)       ; list of all symbols in current context
(symbols 'CTX)  ; list of symbols in context CTX
(symbols CTX)   ; omitting the quote
(set 'ct CTX)   ; assigning context to a variable
(symbols ct)    ; list of symbols in context CTX

コンテキストは、それ自身に評価されるので、クォートを省略できます。
The quote can be omitted because contexts evaluate to themselves.



sync

syntax: (sync int-timeout [func-inlet])
syntax: (sync)

ミリ秒単位の int-timeout を指定された sync は、spawn で起動された子プロセスの終了を待ちます。 子プロセスが終了した時はいつも、sync は、産み出されたサブタスクの評価結果を spawn 宣言文で指定されたシンボルに割り当てます。 sync は、全ての子プロセスがプロセスし終えたなら true を返し、タイムアウト値を越えても多くの子プロセスがペンディング中の時 nil を返します。
When int-timeout in milliseconds is specified, sync waits for child processes launched with spawn to finish. Whenever a child process finishes, sync assigns the evaluation result of the spawned subtask to the symbol specified in the spawn statement. The sync returns true if all child processes have been processed or nil if the timeout value has been reached and more child processes are pending.

syncfunc-inlet に追加のオプション・ユーザ定義 inlet 関数を与えられると、この関数は産み出された子プロセスが戻ってきた時、常に子プロセス ID を引数として呼び出されます。 func-inlet は、ラムダ式か、関数を定義されたシンボルのどちらかになります。
If sync additionally is given with an optional user-defined inlet function in func-inlet, this function will be called with the child process-id as argument whenever a spawned child process returns. func-inlet can contain either a lambda expression or a symbol which defines a function.

パラメータ無しの時の sync は、結果がまだ戻ってきていないペンディング中の子プロセス PID (プロセス指定子) のリストを返します。
Without any parameter, sync returns a list of pending child process PIDs (process identifiers), for which results have not been processed yet.

関数 sync は、MS Windows では使えません。
The function sync is not available on MS Windows.

; wait for 10 seconds and process finished child processes
(sync 10000) 

; wait for the maximum time (~ 1193 hours)
(sync -1) 

(define (report pid)
    (println "process: " pid " has returned"))

; call the report function, when a child returns
(sync 10000 report) ; wait for 10 seconds max

; return a list of pending child processes
(sync)          (245 246 247 248)

; wait and do something else
(until (true? (sync 10 report) )
    (println (time-of-day)))

タイムアウト・パラメータを与えられた sync は、タイムアウトか、子プロセスが戻ってくるか、のどちらか早い方まで止まります。 パラメータ無しか、関数が指定された時、sync は直ちに戻ります。
When sync is given with a timeout parameter, it will block until timeout or until all child processes have returned, whichever comes earlier. When no parameter is specified or a function is specified, sync returns immediately.

関数 sync は、子プロセスの同期とプロセスの並列化のための Cilk API の部品です。 Cilk API の全貌は、関数 spawn のリファレンスを見てください。
The function sync is part of the Cilk API for synchronizing child processes and process parallelization. See the reference for the function spawn for a full discussion of the Cilk API.



sys-error

syntax: (sys-error)
syntax: (sys-error int-error)
syntax: (sys-error 0)

newLISP の走っている OS で発生した最後のエラーを報告します。 報告されるエラーは、newLISP がコンパイルされたプラットフォームで異なります。 プラットフォームの C ライブラリの情報を調べてください。 エラーは、エラー番号とエラー・テキストのリストで報告されます。
Reports the last error generated by the underlying OS which newLISP is running on. The error reported may differ on the platforms newLISP has been compiled for. Consult the platform's C library information. The error is reported as a list of error number and error text.

エラーが起こっていないか、システム・エラー番号がリセットされてる時は、nil が返ります。
If no error has occurred or the system error number has been reset, nil is returned.

int-error0 (zero) より大きい時、その番号とエラー・テキストのリストが返ります。
When int-error is greater 0 (zero) a list of the number and the error text is returned.

エラーをリセットするためには、エラー番号に 0 を指定します。
To reset the error specify 0 as the error number.

システム・リソース領域で使う newLISP の関数が nil を返す時はいつも、下層の理由のチェックに sys-error が使えます。 ファイル操作では、ファイルが存在していないとか、リソース・アクセス時の誤った許可とか、に sys-error がセットされるかもしれません。 エラーの他の理由としては、ファイル・ハンドルやセマフォのようなシステム・リソースの枯渇もありえます。
Whenever a function in newLISP within the system resources area returns nil, sys-error can be checked for the underlying reason. For file operations, sys-error may be set for nonexistent files or wrong permissions when accessing the resource. Another cause of error could be the exhaustion of certain system resources like file handles or semaphores.

;; trying to open a nonexistent file
(open "xyz" "r")   nil

(sys-error)        (2 "No such file or directory")

;; reset errno
(sys-error 0)      (0 "Unknown error: 0")
(sys-error)        nil

last-errornet-error も見てください。
See also last-error and net-error.



sys-info

syntax: (sys-info [int-idx])

int-idx 無しで呼ばれた sys-info は、内部リソース統計値のリストを返します。 10 個の整数が次のステータスを報告します:
Calling sys-info without int-idx returns a list of internal resource statistics. Ten integers report the following status:

offsetdescription
0Lispセルの数
Number of Lisp cells
1Lispセルの最大数、定数
Maximum number of Lisp cells constant
2シンボル数
Number of symbols
3評価/再帰レベル
Evaluation/recursion level
4環境スタック・レベル
Environment stack level
5最大呼び出しスタック数、定数
Maximum call stack constant
6親プロセスの PID または 0
Pid of the parent process or 0
7走っている newLISP プロセスの PID
Pid of running newLISP process
8バージョンを整数で表したもの、定数
Version number as an integer constant
9オペレーティング・システムを表す、定数:
linux=1, bsd=2, osx=3, solaris=4, Windows=6, os/2=7, cygwin=8, tru64, unix=9, aix=10, android=11
    bit 11 は ffilib (extended import/callback API) 版で設定される (add 1024)
    bit 10 は IPv6 版で設定される (add 512)
    bit 9 は 64-bit (changeable at runtime) 版で設定される(add 256)
    bit 8 は UTF-8 版で設定される (add 128)
    bit 7 はライブラリ版で設定される (add 64)
Operating system constant:
linux=1, bsd=2, osx=3, solaris=4, Windows=6, os/2=7, cygwin=8, tru64, unix=9, aix=10, android=11
    bit 11 will be set for ffilib (extended import/callback API) versions (add 1024)
    bit 10 will be set for IPv6 versions (add 512)
    bit 9 will be set for 64-bit (changeable at runtime) versions (add 256)
    bit 8 will be set for UTF-8 versions (add 128)
    bit 7 will be added for library versions (add 64)

0 から 9 は、戻りリストのオプションのオフセットを指しています。
The numbers from 0 to 9 indicate the optional offset in the returned list.

"Maximum call stack constant" までの指定には、オフセット 0 ~ 5 を使い、 残りの四つのエントリのアクセスには、負数のオプセット -1 ~ -4 を使うことを推奨します。 将来、新エントリは、オフセット 5 の後に挿入されるでしょう。 この方法なら、古いソースコードでも変更の必要がありません。
It is recommended to use offsets 0 to 5 to address up and including "Maximum call stack constant" and to use negative offsets -1 to -4 to access the last four entries in the system info list. Future new entries will be inserted after offset 5. This way older source code does not need to change.

int-idx を使えば、リスト中の一要素が返されます。
When using int-idx, one element of the list will be returned.

(sys-info)      (429 268435456 402 1 0 2048 0 19453 10406 1155)
(sys-info 3)    1 
(sys-info -2)   10406 ;; version 10.4.6

Lisp セルの最大数は、コマンド・ラインのスイッチ -m で変更できます。 Lisp セル・メモリ 1メガ・バイト当たり 64k メモリ・セルが割り当てられます。 最大コール・スタック深さは、コマンド・ラインのスイッチ -s を使って、変更できます。
The number for the maximum of Lisp cells can be changed via the -m command-line switch. For each megabyte of Lisp cell memory, 64k memory cells can be allocated. The maximum call stack depth can be changed using the -s command-line switch.



t-test

syntax: (t-test list-vector number-value)
syntax: (t-test list-vector-A list-vector-B [true])
syntax: (t-test list-vector-A list-vector-B float-probability)

第一構文において、この関数は list-vector の平均値と number-value を比較するために、一サンプルのスチューデントの t 検定を使います:
In the first syntax the function uses a one sample Student's t test to compare the mean value of list-vector to the value in number-value:

; one sample t-test
(t-test '(3 5 4 2 5 7 4 3) 2.5)
 '(4.125 2.5 1.552 0.549 2.960 7 0.021)

次のようなデータがリストで返ります:
The following data are returned in a list:

namedescription
meanベクトル・ベクターの平均値
mean of data in vector
value比較する値
value to compare
sdevベクトル・データの標準偏差
standard deviation in data vector
mean-error平均値の標準誤差
standard error of mean
t平均値と値の t 値
t between mean and value
df自由度
degrees of freedom
p帰無仮説下での t の尾部両側の確率
two tailed probability of t under the null hypothesis

上記例では、4.125 の平均値と 2.5 の差がそれなりの意味を持ちます。 確率が p = 0.021 (2.1%) なので、平均値が余り違わないという帰無仮説は破棄されます。
In above example the difference of the mean value 4.125 from 2.5 is moderately significant. With a probability p = 0.021 (2.1%) the null hypothesis that the mean is not significantly different, can be rejected.

第二構文において、この関数は スチューデントの t 統計量を使った t 検定を実行し、list-vector-Alist-vecor-B の平均値を比較します。 true フラグが使われていないなら、A と B のベクトルの大きさが違っていても良く、A と B であらわされる集合体には関連がありません。(訳注:EXCELのTTEST(配列 1,配列 2, 2, 3)に相当)
In the second syntax, the function performs a t-test using the Student's t statistic for comparing the means values in list-vector-A and list-vector-B. If the true flag is not used, both vectors in A and B can be of different length and groups represented by A and B are not related.

オプション・フラグが true に設定されると、測定は同じ集団から二度取られたことになります。たとえば、処理の前と後とか。(訳注:EXCELのTTEST(配列 1,配列 2, 2, 1)に相当)
When the optional flag is set to true, measurements were taken from the same group twice, e.g. before and after a procedure.

次のような結果がリストで返ります:
The following results are returned in a list:

namedescription
mean-a A 集団の平均値
Mean of group A
mean-b B 集団の平均値
Mean of group B
sdev-a A 集団の標準偏差
Standard deviation in group A
sdev-b B 集団の標準偏差
Standard deviation in group B
t平均値間の t 値
t between mean values
df自由度
degress of freedom
p帰無仮説下での t の尾部両側の確率
Two tailed probability of t under the null hypothesis

最初の例は SCAT(Sam の認識能力試験)前の異なる睡眠時間の影響調査です:
The first example studies the effect of different sleep length before a test on the SCAT (Sam's Cognitive Ability Test):

; SCAT (Sam's Cognitive Ability Test) 
; two independent sample t-test
(set 'hours-sleep-8 '(5 7 5 3 5 3 3 9))
(set 'hours-sleep-4 '(8 1 4 6 6 4 1 2))

(t-test hours-sleep-8 hours-sleep-4)
  (5 4 2.138 2.563 0.847 14 0.411)

SCAT 前の睡眠時間は、確率値が 0.411 なのであまり影響がありません。
The duration of sleeps before the SCAT does not have a significant effect with a probability value of 0.411.

二番目の例では、同じ集団の人が Prozac うつ病薬を処方する前と後で二度試験しています:
In the second example, the same group of people get tested twice, before and after a treatment with Prozac depression medication:

; Effect of an antidepressant on a group of depressed people
; two related samples t-test
(set 'mood-pre '(3 0 6 7 4 3 2 1 4))
(set 'mood-post '(5 1 5 7 10 9 7 11 8))

(t-test mood-pre mood-post true)
 (3.333 7 2.236 3.041 -3.143 8 0.0137)

抗うつ薬の処方の効果は、p0.0137 なのでそれなりに効果がありそうです。
The effect of the antidepressant treatment is moderately significant with a p of 0.0137.

第三構文において、この関数はウェルチの t 検定 と呼ばれるスチューデントの t の形式です。 この手法は、両サンプルで観測される分散が著しく違う(訳注:異分散)場合に使われます。 使用する閾値は変数 float-probability に設定できます。 この変数が使われると、t-test は二つのデータ・サンプルの分散を比較する F 検定を実行します。 見つかった F 比 の確率が変数 float-probability 以下なら、ウェルチの t 検定 手法が使えるでしょう。 この比率を1.0 に指定することは、ウェルチの t 検定 を有効にします:
In the third syntax, a form of the Student's t called Welch's t-test is performed. This method is used when the variances observed in both samples are significantly different. The threshold can be set using the float-probability parameter. When this parameter is used the t-test function will perform a F-test to compare the variances in the two data samples. If the probability of the found F-ratio is below the float-probability parameter, the Welch's t-test method will be used. Specifying this value as 1.0 effectively forces a Welch's t-test:

; two independent sample t-test using the Welch method
(t-test '(10 4 7 1 1 6 1 8 2 4) '(4 6 9 4 6 8 9 3) 1.0)
 (4.4 6.125 3.239 2.357 -1.307 15 0.211) 

; two independent sample t-test using the normal method
(t-test '(10 4 7 1 1 6 1 8 2 4) '(4 6 9 4 6 8 9 3))
 (4.4 6.125 3.239 2.357 -1.260 16 0.226)

この二つサンプルの平均値間には、余り違いが認められません。 このケースでは、普通の t 検定手法を使う時よりも、ウェルチ 手法の t 検定の方がわずかに敏感です。
There is no significant difference between the means of the two samples. The Welch method of the t-test is slightly more sensitive in this case than using the normal t-test method.

サンプルの異分散の有意性が特定の値に届いているなら、1.0 より小さい値がウェルチの t 検定 手法の引き金になります。
Smaller values than 1.0 would trigger the Welch's t-test method only when the significance of variance difference in the samples reaches certain value.



tan

syntax: (tan num-radians)

num-radians の正接関数を計算し、結果を返します。
Calculates the tangent function from num-radians and returns the result.

(tan 1)                      1.557407725
(set 'pi (mul 2 (asin 1)))   3.141592654
(tan (div pi 4))             1


tanh

syntax: (tanh num-radians)

num-radians の双曲線正接を計算します。双曲線正接は、次のように定義されます: sinh (x) / cosh (x)
Calculates the hyperbolic tangent of num-radians. The hyperbolic tangent is defined mathematically as: sinh (x) / cosh (x).

(tanh 1)      0.761594156
(tanh 10)     0.9999999959
(tanh 1000)   1
(= (tanh 1) (div (sinh 1) (cosh 1)))   true


term

syntax: (term symbol)

シンボル の名前部分をコンテキスト無しの文字列で返します。
Returns as a string, the term part of a symbol without the context prefix.

(set 'ACTX:var 123)
(set 'sm 'ACTX:var)
(string sm)      "ACTX:var"
(term sm)        "var"

(set 's 'foo:bar)
(= s (sym (term s) (prefix s)))

シンボルから名前空間やコンテキストを取り出す prefix も見てください。
See also prefix to extract the namespace or context prefix from a symbol.



throw

syntax: (throw exp)

関数 catch と一緒に動作します。 throw は、先行する catch 文への戻りを強行し、catch の結果シンボルに exp をおきます。
Works together with the catch function. throw forces the return of a previous catch statement and puts the exp into the result symbol of catch.

(define (throw-test)
    (dotimes (x 1000) 
        (if (= x 500) (throw "interrupted"))))

(catch (throw-test) 'result)   true

result   "interrupted"

(catch (throw-test))   "interrupted"

最後の例は、throw の結果を直接返す catch のショート形式を示しています。
The last example shows a shorter form of catch, which returns the throw result directly.

throw は、ループからの脱出やユーザ定義関数や式ブロックからの早期戻りに有効です。 次の例で、begin ブロックは (foo X)true の時 X を、そうでない時は Y を返します。
throw is useful for breaking out of a loop or for early return from user-defined functions or expression blocks. In the following example, the begin block will return X if (foo X) is true; else Y will be returned:

(catch (begin
    …
    (if (foo X) (throw X) Y)
    …
))

throw は、エラー例外を起こしません 。 ユーザ・エラー例外を出したい時は、throw-error を使ってください。
throw will not cause an error exception. Use throw-error to throw user error exceptions.



throw-error

syntax: (throw-error exp)

exp の評価で供給されるテキストで、ユーザ定義エラー例外を起こします。
Causes a user-defined error exception with text provided by evaluating exp.

(define (foo x y)
    (if (= x 0) (throw-error "first argument cannot be 0"))
    (+ x y))

(foo 1 2)   3

(foo 0 2)  ; causes a user error exception
ERR: user error : first argument cannot be 0
called from user-defined function foo

ユーザ・エラーは、ユーザ定義エラー・ハンドラと関数 error-event、またはエラー例外を捉える catch の形式を使って、他のエラー例外と同じように処理されます。
The user error can be handled like any other error exception using user-defined error handlers and the error-event function, or the form of catch that can capture error exceptions.



time

syntax: (time exp [int-count)

exp の式を評価し、評価に費やした時間をミリ秒単位の浮動小数点で返します。 ミリ秒の小数が現れるかどうかは、プラットフォーム次第です。
Evaluates the expression in exp and returns the time spent on evaluation in floating point milliseconds. Depending on the platform decimals of milliseconds are shown or not shown.

(time (myprog x y z))   450.340

(time (myprog x y z) 10)   4420.021

一番目の例では、(myprog x y z) の評価に 450 ミリ秒かかっています。 二番目の例は、(myprog x y z) の 10回の評価の時間を返します。 datedate-valuetime-of-daynow も見てください。
In first the example, 450 milliseconds elapsed while evaluating (myprog x y z). The second example returns the time for ten evaluations of (myprog x y z). See also date, date-value, time-of-day, and now.



time-of-day

syntax: (time-of-day)

今日の最初からの時間をミリ秒単位で返します。
Returns the time in milliseconds since the start of the current day.

関数 datedate-valuetime、 and now も見てください。
See also the date, date-value, time, and now functions.



timer

syntax: (timer sym-event-handler | func-event-handler num-seconds [int-option])
syntax: (timer sym-event-handler | func-event-handler)
syntax: (timer)

num-seconds で指定された)秒単位の時間経過後に Unix シグナル SIGALRMSIGVTALRMSIGPROF が発火するワン・ショット・タイマーを開始します。 タイマーが発火すると、sym--event-handler のユーザ定義関数か func-event-handler が呼び出されます。
Starts a one-shot timer firing off the Unix signal SIGALRM, SIGVTALRM, or SIGPROF after the time in seconds (specified in num-seconds) has elapsed. When the timer fires, it calls the user-defined function in sym- or func-event-handler.

Linux/Unix では、オプション 0, 1, 2 が、 タイマー・カウント方法の制御用に指定できます。 デフォルトのオプション 0 では、実時間が計測されます。 オプション 1 は、タイマー自身のプロセスで CPU が費やした時間を計測します。 オプション 3 は、profiling time と呼ばれる両方の組み合わせです。 詳細は、Unix man ページの setitimer() を見てください。
On Linux/Unix, an optional 0, 1, or 2 can be specified to control how the timer counts. With default option 0, real time is measured. Option 1 measures the time the CPU spends processing in the process owning the timer. Option 2 is a combination of both called profiling time. See the Unix man page setitimer() for details.

イベント・ハンドラは、イベントの連続的なフローを実行するためにタイマーを再び開始できます。 バージョン 8.5.9 から、秒数は小数点以下の浮動小数点で定義可能です(例えば、 250 ミリ秒は、 0.25)。
The event handler can start the timer again to achieve a continuous flow of events. Starting with version 8.5.9, seconds can be defined as floating point numbers with a fractional part (e.g., 0.25 for 250 milliseconds).

走っているタイマーを止めて発火するのを防ぐには、0 (zero) を指定します。
Defining 0 (zero) as time shuts the running timer down and prevents it from firing.

sym-event-handlerfunc-event-handler で呼ばれた時、timer は進行中のタイマーの消費時間を返します。 これは、プログラム計画や予定に使えます。
When called with sym- or func-event-handler, timer returns the elapsed time of the timer in progress. This can be used to program time lines or schedules.

引数なしのtimer は、現在のイベント・ハンドラのシンボルを返します。
timer called without arguments returns the symbol of the current event handler.

(define (ticker) 
    (println (date)) (timer 'ticker 1.0))

> (ticker)
Tue Apr 12 20:44:48 2005	; first execution of ticker
 ticker			      ; return value from ticker

> Tue Apr 12 20:44:49 2005	; first timer event
Tue Apr 12 20:44:50 2005	; second timer event ...
Tue Apr 12 20:44:51 2005
Tue Apr 12 20:44:52 2005

例は、各イベント後でタイマーが再び開始するイベント・ハンドラ、ticker を示しています。
The example shows an event handler, ticker, which starts the timer again after each event.

組込関数の実行中は、タイマーがインターラプトできないことに注意してください。 タイマー・インターラプトは newLISP に登録されますが、一つの式が評価されて次が開始するまで、タイマー・ハンドラは走ることができません。 timer で実行中の I/O 操作をインターラプトするには、ソケットに読み出し準備ができたかどうかをテストするため、net-select を呼び出す次のパターンを使ってください。
Note that a timer cannot interrupt an ongoing built-in function. The timer interrupt gets registered by newLISP, but a timer handler cannot run until one expression is evaluated and the next one starts. To interrupt an ongoing I/O operation with timer, use the following pattern, which calls net-select to test if a socket is ready for reading:

define (interrupt)
    (set 'timeout true))
        
(set 'listen (net-listen 30001))
(set 'socket (net-accept listen))
        
(timer 'interrupt 10)
;; or specifying the function directly
(timer (fn () (set 'timeout true)) 10)
        
(until (or timeout done)
    (if (net-select socket "read" 100000)
        (begin
            (net-receive socket buffer 1024)
            (set 'done true)))
)
                                                                                
(if timeout
    (println "timeout")
    (println buffer))
                                                                              
(exit)

この例では、until ループは socket から何かを読み取るか、10秒が過ぎて timeout 変数がセットされるまで走ります。
In this example, the until loop will run until something can be read from socket, or until ten seconds have passed and the timeout variable is set.



title-case utf8

syntax: (title-case str [bool])

str の文字列の最初の文字を大文字に変換したコピーを返します。 オプションの bool パラメータが nil 以外の値に評価される時は、文字列の残りを小文字に変換します。
Returns a copy of the string in str with the first character converted to uppercase. When the optional bool parameter evaluates to any value other than nil, the rest of the string is converted to lowercase.

(title-case "hello")        "Hello"
(title-case "hELLO" true)   "Hello"
(title-case "hELLO")        "HELLO"

関数 lower-caseupper-case も見てください。
See also the lower-case and upper-case functions.



trace

syntax: (trace int-device)
syntax: (trace true)
syntax: (trace nil)
syntax: (trace)

第一構文では、パラメータがファイルを開くときのようなデバイスの整数です。 出力をそのデバイスに連続して書き込みます。 int-device1 ならば、出力を標準出力 に書き込みます。
In the first syntax the parameter is an integer of a device like an opened file. Output is continuously written to that device. If int-device is 1 output is written to stdout.

; write all entries and exits from expressions to trace.txt
(trace (open "trace.txt")) 

; write all entries and exits from expressions to trace.txt
(foo x y)                  
(bar x)              
      
; close the trace.txt file
(trace nil)

第二構文では、パラメータが真(true)に評価される時、デバッガ・モードに切り替わります。 デバック・モード中の newLISP は、各エントリ後に止まり、式から抜け出して、ユーザ入力を待ちます。 二つの #(番号記号)文字を使い、式(訳注:直前に実行された式)を囲むことでハイライトを表します。 この文字は trace-highlight を使って、別の文字に変更できます。
In the second syntax debugger mode is switched on when the parameter evaluates true. When in debugging mode newLISP will stop after each entry and exit from an expression and wait for user input. Highlighting is done by bracketing the expression between two # (number sign) characters. This can be changed to a different character using trace-highlight.:

[-> 2] s|tep n|ext c|ont q|uit >

プロンプトの s, n, c, q は、1ステップ進めるか単に次の式を実行するために入力できます。 評価用に如何なる式も入力できます。 例えば、変数の名前を入れると、その内容が評価されます。 このようにして、デバック中の変数の内容をチェックしたり、別な値にセットしたりできます。
At the prompt, an s, n, c, or q can be entered to step into or merely execute the next expression. Any expression can be entered at the prompt for evaluation. Entering the name of a variable, for example, would evaluate to its contents. In this way, a variable's contents can be checked during debugging or set to different values.

;; switches newLISP into debugging mode
(trace true)   true 

;; the debugger will show each step
(my-func a b c)

;; switched newLISP out of debugging mode
(trace nil)   nil 

通常の式をインターラプトし、デバック・モードに入るためのブレイク・ポイントを設定するには、newLISP コード中のデバックに入りたい実行箇所に (trace true) 文を置いてください。
To set break points where newLISP should interrupt normal execution and go into debugging mode, put (trace true) statements into the newLISP code where execution should switch on the debugger.

上記例のショートカットである関数 debug も見てください。
Use the debug function as a shortcut for the above example:

(debug (my-func a b c))

第三構文の (trace nil) はデバック・モードを閉じるか、開かれているトレース・ファイルを閉じます。
In the third syntax (trace nil) closes debugger mode or the trace file opened.

最後の構文 (trace) は現在のモードを返します。
In the last syntax (trace) returns the current mode.



trace-highlight

syntax: (trace-highlight str-pre str-post [str-header str-footer])

trace の間、式を取り囲む文字または文字列を設定します。 デフォルトでは、trace モードのハイライト表現の囲みに # (number sign) が使われます。 これは、異なる文字か7文字までの文字列に変更できます。 コンソール・ウィンドウがターミナル制御文字を受け付けるなら、異なる色、太字、反転文字等で式を表現するために使えます。
Sets the characters or string of characters used to enclose expressions during trace. By default, the # (number sign) is used to enclose the expression highlighted in trace mode. This can be changed to different characters or strings of up to seven characters. If the console window accepts terminal control characters, this can be used to display the expression in a different color, bold, reverse, and so forth.

オプションで、分離とプロンプトを制御する str-header と str-footer に二つ以上の文字列を指定できます。 ヘッダーには最大15文字、フッターには最大31文字が許されます。
Two more strings can optionally be specified for str-header and str-footer, which control the separator and prompt. A maximum of 15 characters is allowed for the header and 31 for the footer.

;; active expressions are enclosed in >> and <<

(trace-highlight ">>" "<<") 
             
;; 'bright' color on a VT100 or similar terminal window

(trace-highlight "\027[1m" "\027[0m")   

第一の例は、デフォルトの # (number sign) を >><< に置き換えています。 二番目の例は、ほとんどの Linux シェルで動作します。 しかしながら、MS Windows や CYGWIN では端末の設定次第で動作しないかもしれません。
The first example replaces the default # (number sign) with a >> and <<. The second example works on most Linux shells. It may not, however, work in console windows under MS Windows or CYGWIN, depending on the configuration of the terminal.



transpose

syntax: (transpose matrix)

matrix の行と列を入れ替える転置を行います。 いかなるリスト行列も転置されます。 リスト内の行でアトムを充当もしくは展開すべき場所、要素の見つからない所や要素の省略された所には、nil を埋めることで、行列は矩形にされます。 置換された行列の次数は、列数は元の行列の行の数を使って、行数は最初の行の要素数を使って算出されます。
Transposes a matrix by reversing the rows and columns. Any kind of list-matrix can be transposed. Matrices are made rectangular by filling in nil for missing elements, omitting elements where appropriate, or expanding atoms in rows into lists. Matrix dimensions are calculated using the number of rows in the original matrix for columns and the number of elements in the first row as number of rows for the transposed matrix.

転置のための行列には、如何なるデータ型も含めることができます。
The matrix to transpose can contain any data-type.

行列の次元は、行数と最初の行の要素数で定義されます。 入れ子のリストと array のどちらも、行列になれます。
The dimensions of a matrix are defined by the number of rows and the number of elements in the first row. A matrix can either be a nested list or an array.

(set 'A '((1 2 3) (4 5 6)))
(transpose A)                       ((1 4) (2 5) (3 6))
(transpose (list (sequence 1 5)))   ((1) (2) (3) (4) (5))

; any data type is allowed in the matrix
(transpose '((a b) (c d) (e f)))    ((a c e) (b d f))

; arrays can be transposed too
(set 'A (array 2 3 (sequence 1 6)))
(set 'M (transpose A)) 
M  ((1 4) (2 5) (3 6))

行列の列数は、行列の最初の行の要素数で定義されます。 行の要素が少ないなら、transpose は見つからなかった要素を nil にします。 行中の余計な要素は、無視されます。
The number of columns in a matrix is defined by the number of elements in the first row of the matrix. If other rows have fewer elements, transpose will assume nil for those missing elements. Superfluous elements in a row will be ignored.

(set 'A '((1 2 3) (4 5) (7 8 9)))

(transpose A)   ((1 4 7) (2 5 8) (3 nil 9))

転置の際、行がリスト以外のデータ型である時は、そのデータ型の要素を行の全ての要素として処理します:
If a row is any other data type besides a list, the transposition treats it like an entire row of elements of that data type:

(set 'A '((1 2 3) X (7 8 9)))

(transpose A)   ((1 X 7) (2 X 8) (3 X 9))

ここに示したすべてのリスト上の操作は、アレイでも実行されます。
All operations shown here on lists can also be performed on arrays.

他の行列操作 detinvertmatmultiply も見てください。
See also the matrix operations det, invert, mat and multiply.



trim utf8

syntax: (trim str)
syntax: (trim str str-char)
syntax: (trim str str-left-char str-right-char)

最初の構文を使えば、str 両端の全ての空白文字が取り除かれます。
Using the first syntax, all white-space characters are trimmed from both sides of str.

第二構文は str 文字列の両端から str-char で与えられた文字を頭と尻尾から取り除きます。 もし str-char がなければ、空白文字となります(訳注:第一構文と同じ)。 trim は新しい文字列を返します。
The second syntax trims the string str from both sides, stripping the leading and trailing characters as given in str-char. If str-char contains no character, the space character is assumed. trim returns the new string.

第三構文は両サイドで異なる文字を切り落とします。 空文字列が指定された時は、反対側の文字のみを切り落とします。
The third syntax can either trim different characters from both sides or trim only one side if an empty string is specified for the other.

(trim "   hello \n ")             "hello"
(trim "   h e l l o   ")          "h e l l o")
(trim "----hello-----" "-")       "hello"
(trim "00012340" "0" "")          "12340"
(trim "1234000" "" "0")           "1234"
(trim "----hello=====" "-" "=")   "hello"

もっと複雑な場合には、replace を使うことができます。 可能でならば、より早い trim を推奨します。
For more complex cases replace can be used. When possible, the much faster trim is preferred.



true?

syntax: (true? exp)

expnil か 空リスト () 以外に評価された時、true?true を返し、それ以外は nil を返します。
If the expression in exp evaluates to anything other than nil or the empty list (), true? returns true; otherwise, it returns nil.

(map true? '(x 1 "hi" (a b c) nil ()))
 (true true true true nil nil)
(true? nil)   nil
(true? '())   nil

true?if のように振る舞い、空リスト () を却下します(訳注:つまり、nil を返す)。
true? behaves like if and rejects the empty list ().



unicode

syntax: (unicode str-utf8)

str のASCII/UTF-8 文字の文字列を 4 バイトの UCS-4–エンコード Unicode に変換します。 文字列の終端は 4 バイト整数 0 です。 この関数は UTF-8 版 newLISP のみで利用できます。
Converts ASCII/UTF-8 character strings in str to UCS-4–encoded Unicode of 4-byte integers per character. The string is terminated with a 4-byte integer 0. This function is only available on UTF-8–enabled versions of newLISP.

(unicode "new") 
 "n\000\000\000e\000\000\000w\000\000\000\000\000\000\000"

(utf8 (unicode "new"))   "new"

ビッグエンディアン の CPU アーキテクチャでは、バイト順が上位からは下位へと逆になります。 関数 unicodeutf8 は、互いに逆関数です。 UCS-4 Unicode を使用中の時のみ、これらの関数が必要になります。 多くのシステムでは、UTF-8 エンコーディングのみです。
On big endian CPU architectures, the byte order will be reversed from high to low. The unicode and utf8 functions are the inverse of each other. These functions are only necessary if UCS-4 Unicode is in use. Most systems use UTF-8 encoding only.



unify

syntax: (unify exp-1 exp-2 [list-env])

exp-1exp-2 を評価し、つなぎ合わせます(訳注;以下、マッチと表す)。複数の式が等しいか、式の一つが(後で他の式に束縛される)非束縛変数ならば、それらの式もマッチします。 式がリストなら、下位式との比較でマッチされます。 非束縛変数は、シンボルと区別するために大文字で始まります unify単一化ユニフィケーション処理に失敗すれば nil を返し、成功すれば変数連想のリストを返します。 束縛される変数がない時、マッチは成功しますが、unify は、空のリストを返します。 newLISP は、出現検査 を正しく適用するため、修正 J. Alan Robinson 単一化ユニフィケーションアルゴリズムを使っています。 この実装にはない一般的な unifcation algorithm bug についての Peter Norvig の論文も見てください。
Evaluates and matches exp-1 and exp-2. Expressions match if they are equal or if one of the expressions is an unbound variable (which would then be bound to the other expression). If expressions are lists, they are matched by comparing subexpressions. Unbound variables start with an uppercase character to distinguish them from symbols. unify returns nil when the unification process fails, or it returns a list of variable associations on success. When no variables were bound, but the match is still successful, unify returns an empty list. newLISP uses a modified J. Alan Robinson unification algorithm with correctly applied occurs check. See also Peter Norvig's paper about a common unifcation algorithm bug, which is not present in this implementation.

バージョン 10.4.0 から、如何なるアトム、リスト、非束縛変数でも、シンボル _ (ASCII 95) がマッチし、束縛しません。
Since version 10.4.0 the underscore symbol _ (ASCII 95) matches any atom, list or unbound variable and never binds.

matchのように、 findrefref-allreplace で、しばしば、unify はファンクタ(関数オブジェクト)のパラメータとして使われます。
Like match, unify is frequently employed as a parameter functor in find, ref, ref-all and replace.

(unify 'A 'A)   ()  ; tautology

(unify 'A 123)   ((A 123))  ; A bound to 123

(unify '(A B) '(x y))   ((A x) (B y))  ; A bound to x, B bound to y

(unify '(A B) '(B abc))   ((A abc) (B abc))  ; B is alias for A

(unify 'abc 'xyz)   nil  ; fails because symbols are different

(unify '(A A) '(123 456))   nil  ; fails because A cannot be bound to different values

(unify '(f A) '(f B))   ((A B))  ; A and B are aliases

(unify '(f A) '(g B))   nil  ; fails because heads of terms are different

(unify '(f A) '(f A B))   nil  ; fails because terms are of different arity

(unify '(f (g A)) '(f B))   ((B (g A)))  ; B bound to (g A)

(unify '(f (g A) A) '(f B xyz))   ((B (g xyz)) (A xyz))  ; B bound to (g xyz) A to xyz

(unify '(f A) 'A)   nil  ; fails because of infinite unification (f(f(f …)))

(unify '(A xyz A) '(abc X X))    nil ; indirect alias A to X doesn't match bound terms

(unify '(p X Y a) '(p Y X X))   '((Y a) (X a)))  ; X alias Y and binding to 'a

(unify '(q (p X Y) (p Y X)) '(q Z Z))   ((Y X) (Z (p X X)))  ; indirect alias

(unify '(A b _) '(x G z))  ((A x) (G b)) ; _ matches atom z 

(unify '(A b c _) '(x G _ z))  ((A x) (G b)) ; _ never binds, matches c and z

(unify '(A b _) '(x G (x y z)))  ((A x) (G b)) ; _ matches list (x y z)

;; some examples taken from http://en.wikipedia.org/wiki/Unification_(computer_science)

unifylist-env にオプションの束縛リスト、または、連想リストを取ることができます。 これは、unify 式が続き、前の unify の束縛結果を含める必要がある時、役立ちます:
unify can take an optional binding or association list in list-env. This is useful when chaining unify expressions and the results of previous unify bindings must be included:

(unify '(f X) '(f 123))   ((X 123))

(unify '(A B) '(X A) '((X 123)))
 ((X 123) (A 123) (B 123))

前の例では、先に、X は、123 に束縛され、第二宣言文中の前束縛 X として含まれます。
In the previous example, X was bound to 123 earlier and is included in the second statement to pre-bind X.

(訳例:
(unify '(A B) '(X A) (unify '(f X) '(f 123)))
 ((X 123) (A 123) (B 123))
(let (alist (unify '(f X) '(f 123)))
  (unify '(A B) '(X A) alist))
 ((X 123) (A 123) (B 123))

Use unify with expandunifyexpand と使う)

変数は、実際には、newLISP の割り当てとして束縛されないことに注意してください。 むしろ、論理的束縛を示す連想リストが返ります。 expand の特殊構文が、実際、これらの表現を束縛された変数に置き換えます:
Note that variables are not actually bound as a newLISP assignment. Rather, an association list is returned showing the logical binding. A special syntax of expand can be used to actually replace bound variables with their terms:

(set 'bindings (unify '(f (g A) A) '(f B xyz)))
 ((B (g xyz)) (A xyz))

(expand '(f (g A) A) bindings)   (f (g xyz) xyz)

; or in one statement
(expand '(f (g A) A) (unify '(f (g A) A) '(f B xyz)))
 (f (g xyz) xyz)

Use unify with bind for de-structuring(構造体の分解に unifybind と使う)

関数 bind は、統合した変数のセットに使われます:
The function bind can be used to set unified variables:

(bind (unify '(f (g A) A) '(f B xyz)))

A  xyz 
B  (g xyz)

これは、構造体の分解に使うことができます:
This can be used for de-structuring:

(set 'structure '((one "two") 3 (four (x y z))))
(set 'pattern '((A B) C (D E)))
(bind (unify pattern structure))

A  one
B  "two"
C  3
D  four
E  (x y z)

unify は連想リストを返し、その連想を bind が束縛します。
unify returns an association list and bind binds the associations.

Model propositional logic with unifyunify で命題論理を構築する)

次の例が示しているのは、unifyexpand を使って、命題論理を構築する方法です:
The following example shows how propositional logic can be modeled using unify and expand:

; if somebody is human, he is mortal -> (X human) :- (X mortal)
; socrates is human -> (socrates human)
; is socrates mortal? -> ?  (socrates mortal)

(expand '(X mortal) 
         (unify '(X human) '(socrates human))) 
 (socrates mortal)

次は、簡易 PROLOG (Programming in Logic) 実装として動作する、より複雑な例です。
The following is a more complex example showing a small, working PROLOG (Programming in Logic) implementation.

;; a small PROLOG implementation

(set 'facts '(
    (socrates philosopher)
    (socrates greek)
    (socrates human)
    (einstein german)
    (einstein (studied physics))
    (einstein human)
))

(set 'rules '(
    ((X mortal) <- (X human))
    ((X (knows physics)) <- (X physicist))
    ((X physicist) <- (X (studied physics)))
))


(define (query trm)
    (or  (when (find trm facts) true) (catch (prove-rule trm))))

(define (prove-rule trm)
    (dolist (r rules)
        (when (list? (set 'e (unify trm (first r))))
            (when (query (expand (last r) e))
                (throw true))))
    nil
)

; try it

> (query '(socrates human))
true
> (query '(socrates (knows physics)))
nil
> (query '(einstein (knows physics)))
true

プログラムは、facts のデータベースと、単にB が事実なら、A は事実である という rules のデータベースを処理します。 事実は、それが facts データベースで見つけられるか、それがルールを使って証明されるかしたら、真だと証明されます。 ルールは入れ子可能で、例えば、誰かが (knows physics) であることを証明するためには、その誰かが physicist であることが真であると証明されなければなりません。 しかし、その人物が studied physics なら、誰かは単に物理学者です。 ルールの左右の項を分けている <- シンボル は要求されず、 ルールのデータベースをより読みやすくするために追加されているだけです。
The program handles a database of facts and a database of simple A is a fact if B is a fact rules. A fact is proven true if it either can be found in the facts database or if it can be proven using a rule. Rules can be nested: for example, to prove that somebody (knows physics), it must be proved true that somebody is a physicist. But somebody is only a physicist if that person studied physics. The <- symbol separating the left and right terms of the rules is not required and is only added to make the rules database more readable.

この実装は、ルールの右側の前提部分に複数項を扱えませんが、異なるマッチを試すために rules データベースのバックトラッキングを扱えます。 ルールの複数の前提でバックトラッキングを扱うのではありません。 例えば、次のルール A if B and C and D で、前提 BC が進み、D で失敗したなら、バックトラッキング機構はD を成功させるため、戻って B または A 項を別の事実またはルールと再 unify することが必要になるかもしれません。
This implementation does not handle multiple terms in the right premise part of the rules, but it does handle backtracking of the rules database to try out different matches. It does not handle backtracking in multiple premises of the rule. For example, if in the following rule A if B and C and D, the premises B and C succeed and D fails, a backtracking mechanism might need to go back and reunify the B or A terms with different facts or rules to make D succeed.

上記アルゴリズムは、prove-ruleの定義から expand を省略し、unifyquery 関数の引数用に e を外に出すことで、異なる書き方ができます。
The above algorithm could be written differently by omitting expand from the definition of prove-rule and by passing the environment, e, as an argument to the unify and query functions.

証明された事実の 学習 は、それらが証明される度に、それらを facts データベースに付け加えることで実装されます。 これは、次の質問群を高速化します。
A learning of proven facts can be implemented by appending them to the facts database once they are proven. This would speed up subsequent queries.

大規模な PROLOG 実装はルールの項目の評価も許されます。 これは、ルールの項目を処理している間に他の仕事をするための関数を実装することを可能にします。 prove-rule は、各ルール項目のシンボルの eval ためのテストを実行できます。
Larger PROLOG implementations also allow the evaluation of terms in rules. This makes it possible to implement functions for doing other work while processing rule terms. prove-rule could accomplish this testing for the symbol eval in each rule term.



union

syntax: (union list-1 list-2 [list-3 ... ])

union は、二つ以上のリストで見つかる区別可能な唯一の要素だけの集合リストを返します。
union returns a unique collection list of distinct elements found in two or more lists.

(union '(1 3 1 4 4 3) '(2 1 5 6 4))    (1 3 4 2 5 6)

他の集合関数differenceintersectuniqueのように、union は元のリストの順序を維持します。
Like the other set functions difference, intersect and unique, union maintains the order of elements as found in the original lists.



unique

syntax: (unique list)

二重化している全ての要素を削除し、list の中で唯一のものだけを返します。
Returns a unique version of list with all duplicates removed.

(unique '(2 3 4 4 6 7 8 7))   (2 3 4 6 7 8)

リストはソートされている必要はありませんが、 ソートされたリストは unique の実行を早くすることに注意してください。
Note that the list does not need to be sorted, but a sorted list makes unique perform faster.

他の集合関数には、differenceintersectunion.があります。
Other set functions are difference, intersect and union.



unless

syntax: (unless exp-condition body)

exp-conditionnil か空リスト () に評価された時のみ、body の宣言文が評価されます。 body の最後の宣言文の結果か、body が実行されなかった時の exp-condition の戻り値が返ります。
The statements in body are only evaluated if exp-condition evaluates to nil or the empty list (). The result of the last expression in body is returned or the return value of exp-condition if body was not executed.

unlesselse 条件を持たないので、if のように、body 中の宣言文を begin でグループ化する必要はありません:
Because unless does not have an else condition as in if, the statements in body need not to be grouped with begin:

(unless (starts-with (read-line) "quit")
	(process (current-line))
	...
	(finish)
)	

関数 when も見てください。
See also the function when.



unpack 

syntax: (unpack str-format str-addr-packed)
syntax: (unpack str-format num-addr-packed)

syntax: (unpack struct num-addr-packed)
syntax: (unpack struct str-addr-packed)

第一パラメータが文字列の時、unpackstr-addr-packed のバイナリ構造か num-addr-packed で指定された変数を str-format のフォーマットを使って newLISP 変数にアンパックします。 unpackpack の逆操作です。 num-addr-packed を使えば、導入された共用ライブライ関数から返される構造体のアンパックが容易になります。
When the first parameter is a string, unpack unpacks a binary structure in str-addr-packed or pointed to by num-addr-packed into newLISP variables using the format in str-format. unpack is the reverse operation of pack. Using num-addr-packed facilitates the unpacking of structures returned from imported, shared library functions.

num-addr-packed で指定された数値が有効メモリ・アドレスでないと、 システム・バス・エラーやセグメンテーション違反が起こりえ、newLISP がクラッシュしたり、不安定な状態になりかねません。
If the number specified in num-addr-packed is not a valid memory address, a system bus error or segfault can occur and crash newLISP or leave it in an unstable state.

第一パラメータが struct で定義したシンボルの時、 unpackstruct で指定されるフォーマットを使います。 str-format を使った unpack は指定された文字の通りにアンパックし、struct を使った unpack は構造体をスキップします(訳注:おそらく、構造体は変化しないということ。packstruct に書き込むので)。 構造体は、データ型と要素の順序とCPUアーキテクチャにより一直線に詰められたバイト群です。 詳細は関数 struct を参照してください。
When the first parameter is the symbol of a struct definition, unpack uses the format as specified in struct. While unpack with str-format literally unpacks as specified, unpack with struct will skip structure aligning pad-bytes depending on data type, order of elements and CPU architecture. Refer to the description of the struct function for more detail.

NULL ポインタを含む構造をアンパックすると、unpack はポインタを文字列に変換しようと試み、エラーが出るでしょう。 NULL ポインタが予想されるなら、構造体定義に void* を使うべきです。
When unpacking structures containing NULL pointers, an error will be thrown when unpack tries to convert the pointer to a string. If NULL pointers are to be expected, void* should be used in the structure definition.

以下の文字でフォーマットを定義します:
The following characters may define a format:

formatdescription
c a signed 8-bit number
b an unsigned 8-bit number
d a signed 16-bit short number
u an unsigned 16-bit short number
ld a signed 32-bit long number
lu an unsigned 32-bit long number
Ld a signed 64-bit long number
Lu an unsigned 64-bit long number
f a float in 32-bit representation
lf a double float in 64-bit representation
sn a string of n null padded ASCII characters
nn n null characters
> switches to big endian byte order
< switches to little endian byte order


(pack "c c c" 65 66 67)   "ABC"
(unpack "c c c" "ABC")    (65 66 67)

(set 's (pack "c d u" 10 12345 56789))
(unpack "c d u" s)   (10 12345 56789)

(set 's (pack "s10 f" "result" 1.23))
(unpack "s10 f" s)   ("result\000\000\000\000" 1.230000019)

(set 's (pack "s3 lf" "result" 1.23))
(unpack "s3 f" s)   ("res" 1.23)

(set 's (pack "c n7 c" 11 22))
(unpack "c n7 c" s)   (11 22))

>< の指定子は、パック及びアンパック時のバイト順、リトルエンディアンビックエンディアン を切り替えるために使えます。
The > and < specifiers can be used to switch between little endian and big endian byte order when packing or unpacking:

;; on a little endian system (e.g., Intel CPUs)
(set 'buff (pack "d" 1))   "\001\000" 

(unpack "d" buff)    (1)
(unpack ">d" buff)   (256)

バイト順の切り替えは、16、32、64ビット・サイズの数値全てに作用します。
Switching the byte order will affect all number formats with 16-, 32-, or 64-bit sizes.

packunpack のフォーマットは、次の例のように同じである必要はありません:
The pack and unpack format need not be the same, as in the following example:

(set 's (pack "s3" "ABC"))
(unpack "c c c" s)   (65 66 67)

この例では、フォーマット指定子間にスペースがあります。 要求事項ではありませんが、可読性を良くします。
The examples show spaces between the format specifiers. Although not required, they can improve readability.

メモリ・アドレスのバッファの大きさがフォーマット文字列による指定より小さい時は、いくつかのフォーマット文字は使われないことになります。
If the buffer's size at a memory address is smaller than the formatting string specifies, some formatting characters may be left unused.

関数 addressget-intget-longget-charget-stringpack も見てください。
See also the address, get-int, get-long, get-char, get-string, and pack functions.



until

syntax: (until exp-condition [body])

exp-condition body の条件を評価し、結果が nil か空リスト () なら、body 中の式が評価されます。 exp-condition の結果が nil か空リスト以外になるまで、評価は繰り返されます。 body で最後に評価された結果が、until 式の戻り値になります。 body が空なら、最後の exp-condition の結果が返ります。 untilは、(while (not …)) のように動作します。
Evaluates the condition in exp-condition. If the result is nil or the empty list (), the expressions in body are evaluated. Evaluation is repeated until the exp-condition results in a value other than nil or the empty list. The result of the last expression evaluated in body is the return value of the until expression. If body is empty, the result of last exp-condition is returned. until works like (while (not …)).

until はシステム繰り返しシンボル $idx も更新します。
until also updates the system iterator symbol $idx.

(device (open "somefile.txt" "read"))
(set 'line-count 0)
(until (not (read-line)) (inc line-count))
(close (device))
(print "the file has " line-count " lines\n")

本体の式群を評価した後 に条件の評価を試したい時は、関数 do-until を使ってください。
Use the do-until function to test the condition after evaluation of the body expressions.



upper-case utf8

syntax: (upper-case str)

大文字に変換した str の文字列のコピーを返します。 国際文字は正しく変換されます。
Returns a copy of the string in str converted to uppercase. International characters are converted correctly.

(upper-case "hello world")   "HELLO WORLD"

関数 lower-casetitle-case も見てください。
See also the lower-case and title-case functions.



utf8

syntax: (utf8 str-unicode)

UCS-4, 4バイト, Unicode文字列 (str) を UTF-8 に変換します。 この関数は UTF-8 版 newLISP でのみ利用可能です。
Converts a UCS-4, 4-byte, Unicode-encoded string (str) into UTF-8. This function is only available on UTF-8–enabled versions of newLISP.

(unicode "new") 
 "n\000\000\000e\000\000\000w\000\000\000\000\000\000\000"

(utf8 (unicode "new"))   "new"

関数 utf8 は、UTF-8 版 newLISP かどうかのテストにも使えます:
The utf8 function can also be used to test for the presence of UTF-8–enabled newLISP:

(if utf8 (do-utf8-version-of-code) (do-ascii-version-of-code))

big endian CPU アーキテクチャでは、バイト順が上位から下位へと逆になります。 utf8unicode は、互いに逆関数です。 UCS-4 Unicode を使用中の時のみ、これらの関数が必要になります。 多くのシステムでは、UTF-8 エンコーディングのみです。
On big endian CPU architectures, the byte order will be reversed from highest to lowest. The utf8 and unicode functions are the inverse of each other. These functions are only necessary if UCS-4 Unicode is in use. Most systems use UTF-8 Unicode encoding only.



utf8len

syntax: (utf8len str)

UTF-8 文字列の文字数を返します。 UTF-8 文字は 1 バイト/ 8 ビットよりも大きくエンコードされています。 utf8len 文字列中の UTF-8 文字数を返します。 この関数は、UTF-8 版 newLISP でのみ利用可能です。
Returns the number of characters in a UTF-8–encoded string. UTF-8 characters can be encoded in more than one 8-bit byte. utf8len returns the number of UTF-8 characters in a string. This function is only available on UTF-8–enabled versions of newLISP.

(utf8len "我能吞下玻璃而不伤身体。")     12
(length "我能吞下玻璃而不伤身体。")       36

関数 unicodeutf8 も 見てください。 上記、中国語テキストは UTF-8 Sampler からのものです。
See also the unicode and utf8 functions. Above Chinese text from UTF-8 Sampler.



uuid

syntax: (uuid [str-node])

UUID (Universally Unique IDentifier) を作成し、返します。 str-node のノード指定なしでは、タイプ 4 の ランダム生成 UUID が返ります。 オプションの str-node パラメータが使われると、タイプ 1 の(訳注:時間ベース) UUID が返ります。 str-node の文字列には、ネットワーク・アダプタからの有効な MAC (Media Access Code) か、ランダムなノード ID を指定します。 ランダムなノード ID が指定された時は、実 MAC 指定子との衝突を避けるために、第一ノード・バイトの最小ビットは 1 にセットしなければなりません。 ノード ID による タイプ 1 の UUID は、タイプスタンプと他のデータから生成されます。 UUID 生成の詳細は、RFC 4122 を見てください。
Constructs and returns a UUID (Universally Unique IDentifier). Without a node spec in str-node, a type 4 UUID random generated byte number is returned. When the optional str-node parameter is used, a type 1 UUID is returned. The string in str-node specifies a valid MAC (Media Access Code) from a network adapter installed on the node or a random node ID. When a random node ID is specified, the least significant bit of the first node byte should be set to 1 to avoid clashes with real MAC identifiers. UUIDs of type 1 with node ID are generated from a timestamp and other data. See RFC 4122 for details on UUID generation.

;; type 4 UUID for any system

(uuid)   "493AAD61-266F-48A9-B99A-33941BEE3607"

;; type 1 UUID preferred for distributed systems

;; configure node ID for ether 00:14:51:0a:e0:bc
(set 'id (pack "cccccc" 0x00 0x14 0x51 0x0a 0xe0 0xbc))

(uuid  id)   "0749161C-2EC2-11DB-BBB2-0014510AE0BC"

uuid 関数の各実施は新しいユニークな UUID をもたらします。 UUID は system-wide shared stable store (RFC 4122 参照) 無しで生成されます。 UUID を生成するシステムがいくつかのノードに配布されるなら、各ノードで異なるノード ID と共にタイプ 1 の生成が使われるべきです。 同じノード上のいくつかのプロセスにとっては、同時刻に要求されたとしても有効な UUID が保証されます。 これは、生成するnewLISP プロセスのプロセス ID が乱数生成器の種の一部になるからです。 タイプ 4 ID が配布システムで使われる時でも、まだ、二つの同一 UUID はありそうもなく、実 MAC アドレスが使われるタイプ 1 の ID ではありえません。
Each invocation of the uuid function will yield a new unique UUID. The UUIDs are generated without system-wide shared stable store (see RFC 4122). If the system generating the UUIDs is distributed over several nodes, then type 1 generation should be used with a different node ID on each node. For several processes on the same node, valid UUIDs are guaranteed even if requested at the same time. This is because the process ID of the generating newLISP process is part of the seed for the random number generator. When type 4 IDs are used on a distributed system, two identical UUID's are still highly unlikely and impossible for type 1 IDs if real MAC addresses are used.



wait-pid

syntax: (wait-pid int-pid [int-options | nil])

int-pid で指定された子プロセスが終わるまで待ちます。 子プロセスは、前もって processfork で開始しています。 int-pid で指定された子プロセスが終わると、pid とステータス値のリストが返ります。 ステータス値は、子プロセスが終了した理由を表します。 戻ったステータス値の説明は、Linux と他の Unix では異なります。 より詳しい情報には、Linux/Unix man ページで waitpid コマンド(newLISP で使っているハイフンは無し)を調べてください。
Waits for a child process specified in int-pid to end. The child process was previously started with process or fork. When the child process specified in int-pid ends, a list of pid and status value is returned. The status value describes the reason for termination of the child process. The interpretation of the returned status value differs between Linux and other flavors of Unix. Consult the Linux/Unix man pages for the waitpid command (without the hyphen used in newLISP) for further information.

int-pid に-1 が指定されると、親プロセスで開始した任意の子プロセスの pid とステータス情報が返ります。 0 が指定されると、wait-pid は呼び出しプロセスとして同じプロセス・グループの子プロセスのみを監視します。 int-pid の他の負数の値は、同じプロセス・グループでint-pid の負の符号として指定されている子プロセスを報告します。
When -1 is specified for int-pid, pid and status information of any child process started by the parent are returned. When 0 is specified, wait-pid only watches child processes in the same process group as the calling process. Any other negative value for int-pid reports child processes in the same process group as specified with a negative sign in int-pid.

int-options にオプションが指定できます。 int-options の整数値の詳細は、Linux/Unix ドキュメントを見てください。 代わりに nil が指定できます。 このオプションは、wait-pid をノン・ブロッキングにし、戻りリストの pid を 0 にして直ちに戻ります。 このオプションは、 -1int-pid パラメータと一緒に戻ってくる子プロセスの繰り返し実行に使えます。
An option can be specified in int-option. See Linux/Unix documentation for details on integer values for int-options. As an alternative, nil can be specified. This option causes wait-pid to be non-blocking, returning right away with a 0 in the pid of the list returned. This option used together with an int-pid parameter of -1 can be used to continuously loop and act on returned child processes.

この関数は、macOS、Linux、Unixライク・オペレーティング・システムでのみ利用できます。
This function is only available on macOS, Linux and other Unix-like operating systems.

(set 'pid (fork (my-process)))  8596

(set 'ret (wait-pid pid))   (8596 0) ; child has exited

(println "process: " pid " has finished with status: " (last ret))

プロセス my-process が開始し、メイン・プログラムは my-process が終わるまで、wait-pid 呼び出しで止まります。
The process my-process is started, then the main program blocks in the wait-pid call until my-process has finished.



when

syntax: (when exp-condition body)

exp-conditionnil 以外や空リスト () 以外に評価された時のみ、body の宣言文が評価されます。 body の最後の式の評価か、body が評価されなかった時の nil か空リスト () が返ります。
The statements in body are only evaluated if exp-condition evaluates to anything not nil and not the empty list (). The result of the last expression in body is returned or nil or the empty list () if body was not executed.

whenelse 条件を持たないので、ifのように body の宣言文は begin でグループ化する必要はありません:
Because when does not have an else condition as in if, the statements in body need not to be grouped with begin:

(when (read-line)
	(set 'result (analyze (current-line)))
	(report result)
	(finish)
)	

関数 unless も見てください。
See also the function unless.



while

syntax: (while exp-condition body)

exp-condition の条件を評価し、結果が nil か空リスト () 以外なら、body 中の式が評価されます。 exp-condition の結果が、nil か空リスト () になるまで、 評価は繰り返されます。 body の最後に評価された結果が while 式の戻り値になります。
Evaluates the condition in exp-condition. If the result is not nil or the empty list (), the expressions in body are evaluated. Evaluation is repeated until an exp-condition results in nil or the empty list (). The result of the body's last evaluated expression is the return value of the while expression.

while は、システム繰り返しシンボル $idx も更新します。
while also updates the system iterator symbol $idx.

(device (open "somefile.txt" "read"))
(set 'line-count 0)
(while (read-line) (inc line-count))
(close (device))
(print "the file has " line-count " lines\n")

本体の式群を評価した後で条件を評価したい時は、関数 do-while を使ってください。
Use the do-while function to evaluate the condition after evaluating the body of expressions.



write !

syntax: (write)
syntax: (write int-file str-buffer [int-size])
syntax: (write str str-buffer [int-size])

第二構文の write は、前以てファイルの open 操作で開いている int-file で指定されたファイルに、str-buffer のバッファから int-size バイト書き込みます。 int-size が指定されない時、sym-buffer または str-buffer の全てのデータが書き込まれます。 writer は、書き込まれたバイト数か、失敗した時の nil を返します。
In the second syntax write writes int-size bytes from a buffer in str-buffer to a file specified in int-file, previously obtained from a file open operation. If int-size is not specified, all data in sym-buffer or str-buffer is written. write returns the number of bytes written or nil on failure.

全てのパラメータを省略すると、write は最後の read-line からの内容を標準出力に書き込みます。
If all parameters are omitted, write writes the contents from the last read-line to standard out (STDOUT).

writewrite-buffer の省略形です。 長い形式は今でも動作しますが、新しいコードでは避けてください。
write is a shorter writing of write-buffer. The longer form still works but is deprecated and should be avoided in new code.

(set 'handle (open "myfile.ext" "write"))
(write handle data 100)   
(write handle "a quick message\n")

この例のコードは、myfile.extdata 内容を 100 バイト書き込みます。
The code in the example writes 100 bytes to the file myfile.ext from the contents in data.

第三構文の write は破壊的文字列追加に使えます:
In the third syntax, write can be used for destructive string appending:

(set 'str "")
(write str "hello world")

str    "hello world"

関数 read も見てください。
See also the read function.



write-char

syntax: (write-char int-file int-byte1 [int-byte2 ... ])

int-byte で指定された1バイトを int-file で指定されたファイル・ハンドラに書き込みます。 ファイル・ハンドラは、前以て open 操作で得て置きます。 各 write-char は、ファイル・ポインタを 1 バイト/ 8 ビットずつ進めます。
Writes a byte specified in int-byte to a file specified by the file handle in int-file. The file handle is obtained from a previous open operation. Each write-char advances the file pointer by one 8-bit byte.

write-char は書かれたバイトの数を返します。
write-char returns the number of bytes written.

(define (slow-file-copy from-file to-file)
    (set 'in-file (open from-file "read"))
    (set 'out-file (open to-file "write"))
    (while (set 'chr (read-char in-file))
        (write-char out-file chr))
     (close in-file)
    (close out-file)
    "finished")

大規模なデータを一度に書き込む際は、関数 printdevice を使ってください。 より高速なファイル・コピー用組込関数 copy-file を、newLISP が既に提供していることに注意してください。 (訳注:つまり、例のようなスクリプトを使うことは、まずありません)
Use the print and device functions to write larger portions of data at a time. Note that newLISP already supplies a faster built-in function called copy-file.

関数 read-char も見てください。
See also the read-char function.



write-file

syntax: (write-file str-file-name str-buffer)

str-file-name のファイルに、str-buffer の内容を一気に書き込み、書き込んだバイト数を返します。
Writes a file in str-file-name with contents in str-buffer in one swoop and returns the number of bytes written.

失敗した時、関数は nil を返します。 ファイルに対して使った時のエラー情報には、sys-error を使います。 URL の場合は、net-error が詳細なエラー情報を与えます。
On failure the function returns nil. For error information, use sys-error when used on files. When used on URLs net-error gives more error information.

(write-file "myfile.enc"
    (encrypt (read-file "/home/lisp/myFile") "secret"))

現ディレクトリ下でファイル myfile が読み取られ、パスワード secret を使って 暗号化されmyfile.enc の新ファイルに書き込まれます。
The file myfile is read, encrypted using the password secret, and written back into the new file myfile.enc in the current directory.

write-file は、 http:// または file:// URL を str-file-name に取ることができます。 http:// が使われる時、write-fileput-url と同様に動作し、同じ追加パラメータを取ることができます:
write-file can take an http:// or file:// URL in str-file-name. When the prefix http:// is used, write-file works exactly like put-url and can take the same additional parameters:

(write-file "http://asite.com/message.txt" "This is a message" )

ファイル message.txt が、リモート・ローケーション http://asite.com に作成され、str-buffer の内容が書き込まれます。 このモードでは、write-file はリモート newLISP サーバー・ノードへのファイル転送に使われます。
The file message.txt is created and written at a remote location, http://asite.com, with the contents of str-buffer. In this mode, write-file can also be used to transfer files to remote newLISP server nodes.

関数 append-fileread-file も見てください。
See also the append-file and read-file functions.



write-line !

syntax: (write-line [int-file [str]])
syntax: (write-line str-out [str]])

str の文字列と行終端文字が、int-file で指定されたデバイスに書き込まれます。 文字列の引数が省略されると、write-lineint-file での最後の read-line の内容を書き込みます。 第一引数も省略されたなら、標準出力 (STDOUT) か device で設定されたデバイスに書き込みます。
The string in str and the line termination character(s) are written to the device specified in int-file. When the string argument is omitted write-line writes the contents of the last read-line to int-file. If the first argument is omitted too then it writes to to standard out (STDOUT) or to whatever device is set by device.

第二構文では、str-out の文字列に各行が追加されます。
In the second syntax lines are appended to a string in str-out.

write-line は、書き込んだバイト数を返します。
write-line returns the number of bytes written.

(set 'out-file (open "myfile" "write"))
(write-line out-file "hello there")
(close out-file)

(set 'myFile (open "init.lsp" "read")
(while (read-line myFile) (write-line))

(set 'str "")
(write-line str "hello")
(write-line str "world")

str    "hello\nworld\n"

一番目の例は、ファイルをオープン/生成し、それに一行書き込み、ファイルを閉じます。 二番目の例は、引数なしの write-line の使い方を示しています。 init.lsp の内容が端末画面に書き込まれます。
The first example opens/creates a file, writes a line to it, and closes the file. The second example shows the usage of write-line without arguments. The contents of init.lsp are written to the console screen.

行終端文字無しでデバイスに書き込む関数 write も見てください。
See also the function write for writing to a device without the line-terminating character.



xfer-event

syntax: (xfer-event sym-event-handler | func-event-handler) syntax: (xfer-event nil)

get-urlpost-urlput-url で開始する、または、loadsaveread-filewrite-fileappend-file のように URL を取ることができるファイル関数で開始する HTTP バイト転送をモニタするために、シンボル sym-event-handler かラムダ関数 func-event-handler の関数を登録します。
Registers a function in symbol sym-event-handler or in lambda function func-event-handler to monitor HTTP byte transfers initiated by get-url, post-url or put-url or initiated by file functions which can take URLs like load, save, read-file, write-file and append-file.

例えば、get-url要求リクエストされるデータ・ブロックが届いた時はいつも、symfunc の関数が転送されたバイト数を引数にして呼ばれます。 post-url や他のデータ送信関数でデータを送信している時も同様に、転送されたデータの各ブロックで symfunc の関数が転送されたバイト数を引数にして呼ばれます。
E.g. whenever a block of data requested with get-url arrives, the function in sym or func will be called with the number of bytes transferred. Likewise when sending data with post-url or any of the other data sending functions, sym or func will be called with the number of bytes transferred for each block of data transferred.

イベントに nil を指定すると、初期のデフォルト状態にリセットされます。
Specifying nil for the event will reset it to the initial default state.

(xfer-event (fn (n) (println "->" n)))
(length (get-url "http://newlisp.org"))

->73
->799
->1452
->351
->1093
->352
->211
->885
->564
->884
->561
->75
->812
->638
->1452
->801
->5
->927
11935

コンピュータの出力は、太字で示されます。 データ・ブロックが受信された時はいつも、そのバイト数が出力されます。 ラムダ関数 func に直接ハンドラ関数を定義する代わりに、関数が定義されているシンボルも使えます:
The computer output is shown in bold. Whenever a block of data is received its byte size is printed. Instead of defining the handler function directory with a lambda function in func, a symbol containing a function definition could have been used:

(define (report n) (println "->" n))
(xfer-event 'report)

これは、HTTP のアップロードやダウンロードで、継続中のバイト転送の進行をモニタするために使えます。
This can be used to monitor the progress of longer lasting byte transfers in HTTP uploads or downloads.



xml-error

syntax: (xml-error)

最後の xml-parse 操作からのエラー情報のリストか、エラーが無かった時の nil を返します。 第一要素は、エラーを表すテキストからなり、第二要素はソース XML テキストの最後の走査位置を示す数値で、0 (zero) から始まります。
Returns a list of error information from the last xml-parse operation; otherwise, returns nil if no error occurred. The first element contains text describing the error, and the second element is a number indicating the last scan position in the source XML text, starting at 0 (zero).

(xml-parse "<atag>hello</atag><fin")   nil

(xml-error)   ("expected closing tag: >" 18)


xml-parse

syntax: (xml-parse string-xml [int-options [sym-context [func-callback]]])

XML 1.0 に適応している well-formed な XML の文字列を解析します。 xml-parse は、DTD 確認を実行しません。 DTD (Document Type Declarations) と命令の処理は、スキップされます。 タイプ ELEMENT, TEXT, CDATA, COMMENT のノードは解析され、newLISP のリスト構造体が返ります。 要素ノードが属性を持たず、子ノードが無い時は、代わりに空リストになります。 属性は、連想リストで返り、assoc を使ってアクセス可能です。 xml-parse が、奇形の XML で失敗した時は、 nil が返り、xml-error がエラー情報のアクセスに使われます。
Parses a string containing XML 1.0 compliant, well-formed XML. xml-parse does not perform DTD validation. It skips DTDs (Document Type Declarations) and processing instructions. Nodes of type ELEMENT, TEXT, CDATA, and COMMENT are parsed, and a newLISP list structure is returned. When an element node does not have attributes or child nodes, it instead contains an empty list. Attributes are returned as association lists, which can be accessed using assoc. When xml-parse fails due to malformed XML, nil is returned and xml-error can be used to access error information.

(set 'xml 
  "<person name='John Doe' tel='555-1212'>nice guy</person>")

(xml-parse xml) 
 (("ELEMENT" "person" 
    (("name" "John Doe") 
     ("tel" "555-1212"))
    (("TEXT" "nice guy"))))

Modifying the translation process.(翻訳処理を変更する)

空白や属性無しリストやコメントを隠すために、オプションで int-options パラメータを指定できます。 タグを文字列からシンボルに変換するためにも使えます。 別関数 xml-type-tags が、XML タグの変換を提供します。 次のオプション番号が使えます:
Optionally, the int-options parameter can be specified to suppress whitespace, empty attribute lists, and comments. It can also be used to transform tags from strings into symbols. Another function, xml-type-tags, serves for translating the XML tags. The following option numbers can be used:

optiondescription
1空白テキスト・タグの隠蔽
suppress whitespace text tags
2空属性リストの隠蔽
suppress empty attribute lists
4コメント・タグの隠蔽
suppress comment tags
8文字列タグをシンボルに変換
translate string tags into symbols
16SXML(S式 XML)属性タグの追加 (@ ...)
add SXML (S-expression XML) attribute tags (@ ...)

オプションは、数値の足し算で組み合わせられます (例えば、3 は、空白テキストのタグ/情報と空属性リストの隠蔽のオプションの組み合わせです)。
Options can be combined by adding the numbers (e.g., 3 would combine the options for suppressing whitespace text tags/info and empty attribute lists).

続く例は、異なるオプションの使われ方を示しています:
The following examples show how the different options can be used:


XML source:
<?xml version="1.0" ?>
<DATABASE name="example.xml">
<!--This is a database of fruits-->
    <FRUIT>
        <NAME>apple</NAME>
        <COLOR>red</COLOR>
        <PRICE>0.80</PRICE>
    </FRUIT>

    <FRUIT>
        <NAME>orange</NAME>
        <COLOR>orange</COLOR>
        <PRICE>1.00</PRICE>
    </FRUIT>

    <FRUIT>
       <NAME>banana</NAME>
       <COLOR>yellow</COLOR>
       <PRICE>0.60</PRICE>
    </FRUIT>
</DATABASE>

Parsing without any options:(オプション無しの解析)

(xml-parse (read-file "example.xml"))
 (("ELEMENT" "DATABASE" (("name" "example.xml")) (("TEXT" "\r\n\t") 
    ("COMMENT" "This is a database of fruits") 
    ("TEXT" "\r\n\t") 
    ("ELEMENT" "FRUIT" () (("TEXT" "\r\n\t\t") ("ELEMENT" "NAME" () 
       (("TEXT" "apple"))) 
      ("TEXT" "\r\n\t\t") 
      ("ELEMENT" "COLOR" () (("TEXT" "red"))) 
      ("TEXT" "\r\n\t\t") 
      ("ELEMENT" "PRICE" () (("TEXT" "0.80"))) 
      ("TEXT" "\r\n\t"))) 
    ("TEXT" "\r\n\r\n\t") 
    ("ELEMENT" "FRUIT" () (("TEXT" "\r\n\t\t") ("ELEMENT" "NAME" () 
       (("TEXT" "orange"))) 
      ("TEXT" "\r\n\t\t") 
      ("ELEMENT" "COLOR" () (("TEXT" "orange"))) 
      ("TEXT" "\r\n\t\t") 
      ("ELEMENT" "PRICE" () (("TEXT" "1.00"))) 
      ("TEXT" "\r\n\t"))) 
    ("TEXT" "\r\n\r\n\t") 
    ("ELEMENT" "FRUIT" () (("TEXT" "\r\n\t\t") ("ELEMENT" "NAME" () 
       (("TEXT" "banana"))) 
      ("TEXT" "\r\n\t\t") 
      ("ELEMENT" "COLOR" () (("TEXT" "yellow"))) 
      ("TEXT" "\r\n\t\t") 
      ("ELEMENT" "PRICE" () (("TEXT" "0.60"))) 
      ("TEXT" "\r\n\t"))) 
    ("TEXT" "\r\n"))))

空白のみからなる TEXT 要素 は、出力を分かりにくくします。 example.xml のデータベースがデータのみを含んでいるなら、空白文字とコメントをオプション (+ 1 2 4) を使って隠蔽できます:
The TEXT elements containing only whitespace make the output very confusing. As the database in example.xml only contains data, we can suppress whitespace, empty attribute lists and comments with option (+ 1 2 4):

Filtering whitespace TEXT, COMMENT tags, and empty attribute lists:(空白 TEXT や COMMENT タグや空の属性リストを振るい落とす)

(xml-parse (read-file "example.xml") (+ 1 2 4))
 (("ELEMENT" "DATABASE" (("name" "example.xml")) ( 
     ("ELEMENT" "FRUIT" (
       ("ELEMENT" "NAME" (("TEXT" "apple"))) 
       ("ELEMENT" "COLOR" (("TEXT" "red"))) 
       ("ELEMENT" "PRICE" (("TEXT" "0.80"))))) 
     ("ELEMENT" "FRUIT" (
       ("ELEMENT" "NAME" (("TEXT" "orange"))) 
       ("ELEMENT" "COLOR" (("TEXT" "orange"))) 
       ("ELEMENT" "PRICE" (("TEXT" "1.00"))))) 
     ("ELEMENT" "FRUIT" (
       ("ELEMENT" "NAME" (("TEXT" "banana"))) 
       ("ELEMENT" "COLOR" (("TEXT" "yellow"))) 
       ("ELEMENT" "PRICE" (("TEXT" "0.60"))))))))

出力結果はより読みやすく見えますが、xml-type-tags 命令を使って XML タイプ・タグ "ELEMENT" と"TEXT" を隠蔽するのはもちろん、タグ "FRUIT", "NAME", "COLOR", "PRICE" の文字列の代わりにシンボルを使うことで、さらに改良されます。
The resulting output looks much more readable, but it can still be improved by using symbols instead of strings for the tags "FRUIT", "NAME", "COLOR", and "PRICE", as well as by suppressing the XML type tags "ELEMENT" and "TEXT" completely using the xml-type-tags directive.

Suppressing XML type tags with xml-type-tags and translating string tags into symbol tags:(xml-type-tags で XML 型タグを抑制し、文字列タグをシンボル・タグに変換する)

;; suppress all XML type tags for TEXT and ELEMENT
;; instead of "CDATA", use cdata and instead of "COMMENT", use !--

(xml-type-tags nil 'cdata '!-- nil) 

;; turn on all options for suppressing whitespace and empty
;; attributes, translate tags to symbols

(xml-parse (read-file "example.xml") (+ 1 2 8))
 ((DATABASE (("name" "example.xml")) 
     (!-- "This is a database of fruits") 
     (FRUIT (NAME "apple") (COLOR "red") (PRICE "0.80")) 
     (FRUIT (NAME "orange") (COLOR "orange") (PRICE "1.00")) 
     (FRUIT (NAME "banana") (COLOR "yellow") (PRICE "0.60"))))

オプション 8 を使って、タグがシンボルに変換される時、 sym-context でコンテキストを指定できます。 コンテキストが指定されないと、全てのシンボルは、現コンテキスト内で作成されます。
When tags are translated into symbols by using option 8, a context can be specified in sym-context. If no context is specified, all symbols will be created inside the current context.

(xml-type-tags nil nil nil nil)
(xml-parse "<msg>Hello World</msg>" (+ 1 2 4 8 16) 'CTX)
 ((CTX:msg "Hello World"))

XML タイプ・タグ TEXT と ELEMENT に nil に指定すると、それらを消すことになります。 同時に、子ノードのリストの括弧が削除され、文字列タグ "FRUIT"、"NAME" などから変換されたタグ・シンボルで始まるリストの要素として、子ノードが現れます。
Specifying nil for the XML type tags TEXT and ELEMENT makes them disappear. At the same time, parentheses of the child node list are removed so that child nodes now appear as members of the list, starting with the tag symbol translated from the string tags "FRUIT", "NAME", etcetera.

Parsing into SXML (S-expressions XML) format:(SXML (S 式 XML) 形式に解析する)

xml-type-tags を使い、オプション番号1, 2, 4, 816 に従って全てのXML タイプ・タグを隠蔽すれば、SXML形式出力が生成されます:
Using xml-type-tags to suppress all XML-type tags—along with the option numbers 1, 2, 4, 8, and 16—SXML formatted output can be generated:

(xml-type-tags nil nil nil nil)
(xml-parse (read-file "example.xml") (+ 1 2 4 8 16))
 ((DATABASE (@ (name "example.xml")) 
    (FRUIT (NAME "apple") (COLOR "red") (PRICE "0.80")) 
    (FRUIT (NAME "orange") (COLOR "orange") (PRICE "1.00")) 
    (FRUIT (NAME "banana") (COLOR "yellow") (PRICE "0.60"))))

元々の XML タグは : で区分けされた名前空間部分を持ち、コロンは newLISP シンボルとして生じる . ドットに変換されます。
If the original XML tags contain a namespace part separated by a :, that colon will be translated into a . dot in the resulting newLISP symbol.

オプション番号 16 を使うと、属性リストに @(アットマーク)が付加されることに注意してください。
Note that using option number 16 causes an @ (at symbol) to be added to attribute lists.

XML 解析の詳細情報には、関数 xml-type-tags も見てください。
See also the xml-type-tags function for further information on XML parsing.

Parsing into a specified context

XML 式を解析する時、オプション 8 が指定されていれば、XML タグは newLISP シンボルに変換されます。 その際、sym-context オプションがシンボル生成用のコンテキストを指定します:
When parsing XML expressions, XML tags are translated into newLISP symbols, when option 8 is specified. The sym-context option specifies the target context for the symbol creation:

(xml-type-tags nil nil nil nil)
(xml-parse (read-file "example.xml") (+ 1 2 4 8 16) 'CTX)
((CTX:DATABASE (@ (CTX:name "example.xml")) 
    (CTX:FRUIT (CTX:NAME "apple") (CTX:COLOR "red") (CTX:PRICE "0.80")) 
    (CTX:FRUIT (CTX:NAME "orange") (CTX:COLOR "orange") (CTX:PRICE "1.00")) 
    (CTX:FRUIT (CTX:NAME "banana") (CTX:COLOR "yellow") (CTX:PRICE "0.60"))))

コンテキストが存在しない時は、生成されます。 存在する場合、クォートは省略でき、コンテキストは変数で参照できます。
If the context does not exist, it will be created. If it exists, the quote can be omitted or the context can be referred to by a variable.

Using a call back function(コールバック関数を使う)

通常、xml-parse は、解析が終了するまで戻りません。 func-callback オプションを使えば、生成されたS式で閉じた各タグとソース XML 上での先頭からの位置と長さを引数にして、xml-parse はコールバックします:
Normally, xml-parse will not return until all parsing has finished. Using the func-callback option, xml-parse will call back after each tag closing with the generated S-expression and a start position and length in the source XML:

;; demo callback feature
(define (xml-callback s-expr start size)
    (if (or (= (s-expr 0) 'NAME) (= (s-expr 0) 'COLOR) (= (s-expr 0) 'PRICE))
        (begin
            (print "parsed expression:" s-expr)
            (println ", source:" (start size example-xml))
        )
    )
)

(xml-type-tags nil 'cdata '!-- nil)
(xml-parse  (read-file "example.xml") (+ 1 2 8) MAIN xml-callback)

コールバック関数 xml-callback によって、次の出力が生成されます:
The following output will be generated by the callback function xml-callback:

parsed expression:(NAME "apple"), source:<NAME>apple</NAME>
parsed expression:(COLOR "red"), source:<COLOR>red</COLOR>
parsed expression:(PRICE "0.80"), source:<PRICE>0.80</PRICE>
parsed expression:(NAME "orange"), source:<NAME>orange</NAME>
parsed expression:(COLOR "orange"), source:<COLOR>orange</COLOR>
parsed expression:(PRICE "1.00"), source:<PRICE>1.00</PRICE>
parsed expression:(NAME "banana"), source:<NAME>banana</NAME>
parsed expression:(COLOR "yellow"), source:<COLOR>yellow</COLOR>
parsed expression:(PRICE "0.60"), source:<PRICE>0.60</PRICE>

この例のコールバック関数は、注目すべきタグをフィルタし、それらが出現した時に処理します。
The example callback handler function filters the tags of interest and processes them as they occur.



xml-type-tags

syntax: (xml-type-tags [exp-text-tag exp-cdata-tag exp-comment-tag exp-element-tags])

XML のタイプ・タグ "TEXT"、"CDATA"、"COMMENT"、"ELEMENT" を完全に隠蔽するか、パラメータで指定した何かに置き換えることが可能です。
Can suppress completely or replace the XML type tags "TEXT", "CDATA", "COMMENT", and "ELEMENT" with something else specified in the parameters.

xml-type-tags は、タグ自身を隠蔽もしくは変換しますが、タグされた情報を隠蔽したり、変更したりはしません。 後者は、xml-parse にオプション番号を使ってなされます。
Note that xml-type-tags only suppresses or translates the tags themselves but does not suppress or modify the tagged information. The latter would be done using option numbers in xml-parse.

引数無しの xml-type-tags は、現在のタイプ・タグを返します:
Using xml-type-tags without arguments returns the current type tags:

(xml-type-tags)   ("TEXT" "CDATA" "COMMENT" "ELEMENT")

(xml-type-tags nil 'cdata '!-- nil)

一番目の例は、現在使用しているタイプ・タグを返します。 二番目の例は、"TEXT" と "ELEMENT" を隠し、"CDATA" と "COMMENT" の代わりに cdata!-- を示します。
The first example just shows the currently used type tags. The second example specifies suppression of the "TEXT" and "ELEMENT" tags and shows cdata and !-- instead of "CDATA" and "COMMENT".



zero?  bigint

syntax: (zero? exp)

exp の評価が 0(ゼロ)かどうかをチェックします。
Checks the evaluation of exp to see if it equals 0 (zero).

(set 'value 1.2)
(set 'var 0)
(zero? value)   nil
(zero? var)     true

(map zero? '(0 0.0 3.4 4))   (true true nil nil)

(map zero? '(nil true 0 0.0 "" ()))   (nil nil true true nil nil)

数値以外のデータ型において、zero?nil を返します。
zero? will return nil on data types other than numbers.



 )





newLISP APPENDIX(付録)

Error codes(エラー コード)

descriptionno
not enough memory1
environment stack overflow2
call stack overflow3
problem accessing file4
not an expression5
missing parenthesis6
string token too long7
missing argument8
number or string expected9
value expected10
string expected11
symbol expected12
context expected13
symbol or context expected14
list expected15
list or array expected16
list or symbol expected17
list or string expected18
list or number expected19
array expected20
array, list or string expected21
lambda expected22
lambda-macro expected23
invalid function24
invalid lambda expression25
invalid macro expression26
invalid let parameter list27
problem saving file28
division by zero29
matrix expected30
wrong dimensions31
matrix is singular32
syntax in regular expression33
throw without catch34
problem loading library35
import function not found36
symbol is protected37
error number too high38
regular expression39
missing end of text [/text]40
mismatch in number of arguments41
problem in format string42
data type and format don't match43
invalid parameter44
invalid parameter: 0.045
invalid parameter: NaN46
invalid UTF8 string47
illegal parameter type48
symbol not in MAIN context49
symbol not in current context50
target cannot be MAIN51
list index out of bounds52
array index out of bounds53
string index out of bounds54
nesting level too deep55
list reference changed56
invalid syntax57
user error58
user reset -59
received SIGINT -60
function is not reentrant61
local symbol is protected62
no reference found63
list is empty64
I/O error65
working directory not found66
invalid PID67
cannot open socket pair68
cannot fork process69
no comm channel found70
ffi preparation failed71
invalid ffi type72
ffi struct expected73
bigint type not applicable74
not a number or infinite75
cannot convert NULL to string76




TCP/IP and UDP Error Codes

nodescription
1Cannot open socket
2DNS resolution failed
3Not a valid service
4Connection failed
5Accept failed
6Connection closed
7Connection broken
8Socket send() failed
9Socket recv() failed
10Cannot bind socket
11Too many sockets in net-select
12Listen failed
13Badly formed IP
14Select failed
15Peek failed
16Not a valid socket
17Cannot unblock socket
18Operation timed out
19HTTP bad formed URL
20HTTP file operation failed
21HTTP transfer failed
22HTTP invalid response from server
23HTTP no response from server
24HTTP document empty
25HTTP error in header
26HTTP error in chunked format




System Symbols and Constants(システム シンボルと定数)

Variables changed by the system(システムが変更する変数)

newLISP は内部シンボル変数をいくつか持っています。 それらは全てグローバルで、プログラマーの使用が可能です。 ライト・プロテクションのかかっているものも有りますが、それ以外はユーザで設定可能です。 それを使って閉じている式の部分式に使われている時、変化するものも有ります。 その以外は、入れ子になった関数や式で再帰に使っても安全です。
newLISP maintains several internal symbol variables. All of them are global and can be used by the programmer. Some have write protection, others are user settable. Some will change when used in a sub-expression of the enclosing expression using it. Others are safe when using reentrant in nested functions or expressions.

関数 save または source を使う時、$ 文字で始まる全てのシンボルは直列化シリアライズされません。
All symbols starting with the $ character will not be serialized when using the save or source functions.

 variable namepurpose protected  reentrant 
 $0 - $15主に正規表現で使用されます。$0 は最後の状態の記録に使われます。また、実行回数の記録に使用する関数も有ります。
Used primarily in regular expressions. $0 is also used to record the last state or count of execution of some functions.
 no no
 $argsローカルに束縛されていないパラメータのリストが入っています。この変数の内容の取り出しには、普通、関数 args を使います。
Contains the list parameters not bound to localvariables. Normally the function args is used to retrieve the contents of this variable.
 yes yes
 $countfind-allreplaceref-allset-ref-all で一致した要素数。もしくは read-expr で処理された文字数。
The count of elements matching when using find-all, replace,ref-all and set-ref-all or the count of characters processed by read-expr.
 yes no
 $idx関数 dolist は、リストのインデックスやオプセットとしてこれを使います。関数 mapserieswhileuntildo-whiledo-until は、最初が 0(ゼロ)から始まる繰り返し回数として、この変数を使います。
The function dolistmaintains this as a list index or offset. The functions map, series, while, until, do-while and do-until maintain this variable as an iteration counter starting with 0 (zero) for the first iteration.
 yes yes
 $itアナフォリック $it は、実行中の式内部の結果を参照します。すなわち、自己参照です。$it は、それを設定する関数式内部でのみ利用可能で、その式外では nil に設定されています。次の関数で利用可能です:ifhashesfind-allreplaceset-refset-ref-allsetf、setq
The anaphoric $it refers to the result inside an executing expression, i.e. in self referential assignments. $it is only available inside the function expression setting it, and is set to nil on exit of that expression. The following functions use it:if,hashes, find-all,replace, set-ref, set-ref-all and setf setq.
 yes no
 $main-argsOS によって newLISP に渡されるコマンド・ラインの引数がリストで入っています。内容の取り出しには、通常、関数 main-args を使います。
Contains the list of command line arguments passed by the OS to newLISP when it was started. Normally the function main-args is used to retrieve the contents.
 yes n/a

Predefined variables and functions.(予め定義されている変数と関数)

これらは、予め設定されているシンボル定数です。 そのうち二つは名前空間テンプレートとして使われ、もう一つはプラットフォーム非依存コードを書くために使われます。
These are preset symbol constants. Two of them are used as namespace templates, one to write platform independent code.

namepurpose protected  reentrant 
 Class予め定義された一般 FOOP クラス・コンストラクタで、新 FOOP クラスを生成するために new と一緒に使われます。例えば、(new Class 'Rectangle) はユーザ・クラス Rectangle のクラスとオブジェクト・コンストラクタを生成します。詳細は、ユーザ・マニュアルの FOOP classes and constructors の章で見てください。
Is the predefined general FOOP class constructor which can be used together with new to create new FOOP classes, e.g:(new Class 'Rectangle) would create a class and object constructor for a user class Rectangle. See the FOOP classes and constructors chapter in the users manual for details.
 no n/a
 ostype走っている newLISP の版がコンパイルされた OS-プラットフォームを示す文字列が入っています。詳細はリファレンス・セクションで見てください。
Contains a string identifying the OS-Platform for which the running newLISP version has been compiled. See the reference section for details
 yes n/a
 Tree予め定義されている名前空間で、ハッシュ・ライク辞書を提供するものです。Foo 辞書を生成するために (define Foo:Foo) と書く代わりに、式 (new Tree 'Foo) を同じように使えます。詳細は、Hash functions and dictionaries の章で見てください。
Is a predefined namespace to serve as a hash like dictionary. Instead of writing (define Foo:Foo) to create a Foo dictionary, the expression (new Tree 'Foo) can be used as well. See the chapter Hash functions and dictionaries for details.
 no n/a
 module予め定義されているロード・モジュール用関数です。NEWLISPDIR 環境変数と一緒に load を使う代わりに、関数 module は自動的に $NEWLISPDIR/modules/ からロードします。
Is a predefined function to load modules. Instead of using load together with the NEWLISPDIR environment variable, the module function loads automatically from $NEWLISPDIR/modules/.
 no n/a

シンボル ClassTreemodule は、予め次のように定義されています:
The symbols Class, Tree and module are predefined as follows:

; built-in template for FOOP constructors
; usage: (new Class 'MyClass)
(define (Class:Class) 
    (cons (context) (args)))

; built-in template for hashes
; usage: (new Tree 'MyHash)
(context 'Tree) 
  (constant 'Tree:Tree) 
(context MAIN)"

; load modules from standard path
; usage (module "mymodule.lsp")
(define (module $x)
  (load (append (env "NEWLISPDIR") "/modules/" $x)))

(global 'module)

これらのシンボルは保護されていませんし、ユーザが再定義できます。 変数 $x は組み込みで、削除からも保護されています。 この変数 $xcurry 式でも使えます。
These symbols are not protected and can be redefined by the user. The $x variable is built-in and protected against deletion. This $x variable is also used in curry expressions.



 )



GNU Free Documentation License

Version 1.2, November 2002

Copyright (C) 2000,2001,2002 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.



0. PREAMBLE

The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.

We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.

1. APPLICABILITY AND DEFINITIONS

This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.

A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.

A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.

The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.

A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque".

Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.

The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.

A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.

The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.

2. VERBATIM COPYING

You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.

3. COPYING IN QUANTITY

If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.

4. MODIFICATIONS

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.

B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.

C. State on the Title page the name of the publisher of the Modified Version, as the publisher.

D. Preserve all the copyright notices of the Document.

E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.

F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.

G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice.

H. Include an unaltered copy of this License.

I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.

J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.

K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.

L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.

M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version.

N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section.

O. Preserve any Warranty Disclaimers.

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.

5. COMBINING DOCUMENTS

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.

In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements."

6. COLLECTIONS OF DOCUMENTS

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.

7. AGGREGATION WITH INDEPENDENT WORKS

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.

8. TRANSLATION

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.

If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

9. TERMINATION

You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

10. FUTURE REVISIONS OF THIS LICENSE

The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.








GNU GENERAL PUBLIC LICENSE

Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc. http://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

Preamble

The GNU General Public License is a free, copyleft license for software and other kinds of works.

The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

Developers that use the GNU GPL protect your rights with two steps:

(1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.

Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.

Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS

0. Definitions.

"This License" refers to version 3 of the GNU General Public License.

"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.

"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.

To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.

A "covered work" means either the unmodified Program or a work based on the Program.

To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.

To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.

An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.

1. Source Code.

The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.

A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.

The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.

The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.

The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.

The Corresponding Source for a work in source code form is that same work.

2. Basic Permissions.

All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.

You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.

Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

3. Protecting Users' Legal Rights From Anti-Circumvention Law.

No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.

When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.

4. Conveying Verbatim Copies.

You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.

You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.

5. Conveying Modified Source Versions.

You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.

A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.

6. Conveying Non-Source Forms.

You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:

a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.

A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.

A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.

"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.

If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).

The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.

Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.

7. Additional Terms.

"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.

When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.

Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:

a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.

All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.

If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.

Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.

8. Termination.

You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.

9. Acceptance Not Required for Having Copies.

You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.

10. Automatic Licensing of Downstream Recipients.

Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.

An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.

You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.

11. Patents.

A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".

A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.

Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.

In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.

If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.

If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.

A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.

Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.

12. No Surrender of Others' Freedom.

If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.

13. Use with the GNU Affero General Public License.

Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.

14. Revised Versions of this License.

The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.

If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.

Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.

15. Disclaimer of Warranty.

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

16. Limitation of Liability.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

17. Interpretation of Sections 15 and 16.

If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.


END OF TERMS AND CONDITIONS



 )