!
+-*/%
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
newLISP は、Lisp の主要構成要素:
リスト、シンボル、ラムダ式、に焦点を合わせています。
これらに newLISP は、アレイ と
リストやアレイ上の 暗黙的インデクシング と
ダイナミック(訳注:動的ともいう) 及び レキシカル(訳注:静的または構文的ともいう)スコーピング を追加しています。
レキシカル・スコーピングは、
コンテキスト と呼ばれる独立した名前空間を使って実装しています。(訳注:名前空間 コンテキスト は、ダイナミック・スコープで fexprs を使う時の安全性を提供します。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 です。
200k 強のサイズと、newLISP は、最も一般的な 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, 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) での Classes 定義、
(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 以上に、データ = プログラム パラダイムと完全な自己リフレクション(reflection)を実装します。
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 Artifial Intelligence applications.
newLISP は、複雑な入れ子 リストや多次元 アレイ構造内の要素を
変更、挿入、削除する関数を持っています。
newLISP has functions to modify, insert, or delete elements inside
complex nested lists or multi-dimensional array structures.
newLISP では、文字列がヌル文字を含むことができるので、多くの文字列操作関数を用いてバイナリ・データ処理に使えます。
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 ソケット・インターフェイスは、
ネットワーク分散アプリケーションを書き易くします。
組込 XML インターフェース は、
テキスト処理機能— Perl コンパチブル正規表現 (PCRE) とテキスト解析関数—と一緒に、
newLISP を有用な 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 は、ネットワーク上の分散処理と
1個以上のコアを持つ 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, Mac OS X/Darwin, BSDs, Solaris, Win32 でコンパイルされます。
newLISP は、完全な64ビットメモリアドレッシング用の 64ビット
LP64
アプリケーションとしてコンパイルされます。
The source distribution can be compiled for Linux, Mac OS X/Darwin, BSDs
Solaris, and Win32. newLISP can be compiled as a 64-bit LP64 application for
full 64-bit memory addressing.
newLISP-GS は、グラフィカル・ユーザ・インタフェース (GUI) とライブラリ・サーバーからなります。
ライブラリ・サーバーが、Java ベースで全ての Windows と Mac OS X プラットフォーム上で
インストールされている標準 Java ランタイム環境を使うのに対して、
GUI フロント・エンドは、newLISP で書かれています。
newLISP-GS で構築されたアプリケーションは、
ホスト・コンピュータ・システムのネイティブのルック・アンド・フィールを持つことが可能です。
GTK, Tcl/Tk. OpenGL グラフィックス・ライブラリも利用可能です。
newLISP-GS comprises a graphical user interface (GUI) and library server. The
GUI front-end is written in newLISP, whereas the library server is Java based
and uses the standard Java runtime environment installed on all Windows and
Mac OS X platforms. Applications built with newLISP-GS can have the host operating
system's native look and feel. Interfaces to GTK, Tcl/Tk and OpenGL graphics
libraries are also available.
newLISP と Java は、多くのオペレーティングシステムで利用可能です。
これは、newLISP-GS を GUI アプリケーションを書くためのプラットフォーム非依存解決策にします。
newLISP and Java are available for most operating systems. This makes
newLISP-GS a platform-independent solution for writing GUI applications.
newLISP-GS のさらなる情報は、
newLISP-GS を見て下さい。(訳注:フレーム版はこちらで)
For more information on newLISP-GS, see
newLISP-GS.
newLISP と newLISP-GS は、
GPL (General Public License) 第3版の下でライセンスされます。
newLISP 文書は、newLISP と共にパッケージされた他の文書と同様に
GNU Free Documentation License の下でライセンスされます。
newLISP and newLISP-GS 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.
バージョン 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.
関数 if-not と local はドキュメントから外されます。両関数ともしばらくは動作可能です。(訳注:いずれ無くなるということでしょう)
The functions if-not and local are deprecated and have
been taken out of the documentation. Both functions will keep on working
for an indefinite time.
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 mult-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コマンド・ターミナル・ウィンドウかコマンド・シェルでのみ可能です。
Java ベースの newLISP-GS IDE は、複数行を受け入れません。
Note, that multi-line mode is only possible in an OS command terminal window
or command shell. The monitor window in the Java based newLISP-GS IDE will not
accept multi-line statements.
インタラクティブ Lisp モードは、オペレーティング・システムのシェル・コマンドを受け付けます。
OS コマンドを入力するには、プロンプトの右後に '!' 文字を入力し、シェル・コマンドを続けます:
Intercative 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 が、走ります。
この '!' を使ったモードは、newLISP-GS IDE からも使えます。
The program foo.lsp is now run. This mode using '!' can
also be used from the newLISP-GS IDE.
UNIX 端末やコマンド・シェルを使っている時、組込 newLISP 機能の tab 拡張を使えば:
When using a Unix teminal 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.
コマンドラインから 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 -n no init (must be first) -s <stacksize> -m <max-mem-megabyte> -e <quoted lisp expression> -l <path-file> log connections -L <path-file> log all -w <working-directory> -c no prompts, HTTP -C force prompts -t <microsec-timeout> -p <port-number> -d <port-number> -http HTTP only -6 set 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 システム上で、newlisp の man page があります:
On Linux and other Unix systems, a newlisp man page can be found:
man newlisp
これは、Linux/Unix シェルでマニュアル・ページを表示します。
This will display a man page in the Linux/Unix shell.
newLISP は、コマンドラインで指定されたファイルをロードして実行します。
ファイルは、ローカル・ファイル上のパス名か file:// URL のどちらか
または、HTTP サーバーが走っているリモート・ファイル・システム上の http:// URL で指定されます。
HTTP サーバーは、HTTP サーバー・モードで走っている newLISP で可能です。
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 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
このオプションは、初期化ファイル 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
さらに、initialization files について。
(訳注:リンク先に init.lsp の説明があります。)
More about initialization files.
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.
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.
newLISP の小さい部品は、コマンドラインから直接実行できます:
Small pieces of newLISP code can be executed directly from the command-line:
newlisp -e "(+ 3 4)" → 7 ; On Win32 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.
どのモードでも、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 mode | command-line and net-eval with -c | HTTP 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.
-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.
コマンドライン・プロンプトと始めのコピーライト表示が抑制されます:
The command-line prompt and initial copyright banner can be suppressed:
newlisp -c
ログ状態でないなら、待ち受けと接続のメッセージが抑制されます。
-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 GET、
PUT、
POST、
DELETE 要求に返答する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 マシンでサーバーを可能にする
inetd や
xinetd で newLISP を走らせる時は、
次のように使います:
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.
大文字 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 some.lsp -p 9090
この例は、newLISPがTCP/IPソケット接続上のコマンドを待ち受けられる方法を示しています。
この場合、標準 I/O は、-p オプションで指定されるポートへリダイレクトされます。
some.lsp は、
スタートアップ時、接続開始の待ち受け前にロードされるオプション・ファイルです。
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 GUI フロントエンドや他の言語で書かれたプログラムのような
他のアプリケーションから newLISP を制御するために使われます。
制御しているクライアントが接続を閉じるとすぐに、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.
telnet アプリケーションは、サーバーとして走っている newLISP のテストに使われます。
最初に次を入力します:
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.
-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 は終了しません。
代わりに、メモリにとどまり、新しい接続を待ち受け、その状態を維持します。
クライアント・アプリケーションから発行された 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 サーバー・ノードは、
HTTP GET, PUT, DELETE 要求の返答もします。
これは、
get-url,
put-url,
delete-url,
read-file,
write-file,
append-file と一緒にファイルの引き出しや保存に使われ、
また、load と save を使っての
リモート・サーバー・ノードへのプログラムのロードとセーブに使われます。
詳細は、 -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 を使うことで、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 機で inetd または xinetd 可能なサーバーとして
newLISP が走っている時、次を使って下さい:
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 extension | media type |
|---|---|
| .avi | video/x-msvideo |
| .css | text/css |
| .gif | image/gif |
| .htm | text/htm |
| .html | text/html |
| .jpg | image/jpg |
| .js | application/javascript |
| .mov | video/quicktime |
| .mp3 | audio/mpeg |
| .mpg | video/mpeg |
| application/pdf | |
| .png | image/png |
| .wav | audio/x-wav |
| .zip | application/zip |
| any other | text/plain |
CGI を提供するために、HTTP サーバー・モードは、
Unix ライク・プラットフォームでは /tmp ディレクトリを、
Win32 では 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 Win32. 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、SERVER_SOFTWARE、QUERY_STRING が設定されます。
クライアントから送られた HTTP ヘッダに存在するなら、変数 CONTENT_TYPE、CONTENT_LENGTH、HTTP_HOST、HTTP_USER_AGENT、HTTP_COOKIE も設定されます。
In both server modes -c and -http the environment variables
DOCUMENT_ROOT, REQUEST_METHOD, 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.
-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-connect,
net-listen,
net-eval のローカル・デーモン・ソケット・モードと一緒に動作します。
net-connect と net-listen で開かれたローカル・デーモン・ソケットは、
net-accept,
net-receive,
net-send を使って提供されます。
ローカル・デーモン・ソケットは、
net-peek と net-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 ネットワーク接続よりも高速で、
同じローカルファイルシステム上のプロセス間通信に向いています。
このモードは、Win32 では、利用できません。
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 Win32.
-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.
事実上全ての 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.
二つのファイル:services と inetd.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/bin/newlisp -c # as an alternative, a program can also be preloaded net-eval stream tcp nowait root /usr/bin/newlisp -c myprog.lsp
root の代わりに、別のユーザとオプション・グループを指定できます。
詳細は、inetd のUnix マニュアル・ページを見て下さい。
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
Mac OS X と いくつかの Unix システムでは、
inetd の代わりに xinetd を使うことができます。
次の内容を /etc/xinetd.d/ ディレクトリに
net-eval と名付けたファイルで保存します:
On Mac OS X 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/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.
他の構成オプションは、
xinetd と xinetd.conf のマニュアル・ページを見て下さい。
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 GET と PUT のリクエストに返答します。
これは、
get-url、
put-url、
read-file、
write-file、
append-file
によるファイルの取り出しや保存、および、
load と
save を使っての
リモート・サーバ・ノードへのプログラムのロードとセーブを
可能にします。
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.
スタートアップ中、newLISP は、環境変数 NEWLISPDIR がまだセットされていないなら、セットします。
Linux、BSDs、Mac OS X、その他のUnix 上では、変数は、/usr/share/newlisp にセットされます。
Win32 上では、変数は、%PROGRAMFILES%/newlisp にセットされます。
During startup, newLISP sets the environment variable NEWLISPDIR, if it is
not set already. On Linux, BSDs, Mac OS X and other Unixes the variable is set to
/usr/share/newlisp. On Win32 the variable is set to
%PROGRAMFILES%/newlisp.
環境変数 NEWLISPDIR は、newLISP と一緒にインストールされたファイルをロードする時、役立ちます:
The environment variable NEWLISPDIR is useful when loading files installed with
newLISP:
(load (append (env "NEWLISPDIR") "/guiserver.lsp")) (load (append (env "NEWLISPDIR") "/modules/mysql.lsp"))
modules/ ディレクトリからロードする二番目の宣言文を短くするのに、
予め定義されている関数 module を使うことができます:
A predefined function module can be used to shorten
the second statement loading from the modules/
directory:
(module "mysql.lsp")
コマンドラインで指定されたファイルをロードする前、そして、バナーやプロンプトが示される前に、
newLISP は、ホーム・ディレクトリから .init.lsp のロードを試みます。
Mac OS X、Linux、その他 Unix では、ホーム・ディレクトリは、HOME 環境変数で見つかります。
Win32 では、このディレクトリ名は、環境変数 USERPROFILE か DOCUMENT_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 Mac OS X, Linux and other
Unix the home directory is found in the HOME environment variable.
On Win32 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 のどちらも、
ロードされないことに注意して下さい。
Note that neither one of the initialization files init.lsp nor
.init.lsp is loaded during startup of linked programs.
/usr/share/newlisp/modules ディレクトリには、POP3 mail等の有用な関数群のモジュールが入っています。
/usr/share/newlisp/guiserver ディレクトリには、newLISP-GS で書かれた GUI アプリケーション用のサンプル・プログラムが入っています。
/usr/share/doc/newlisp/ ディレクトリには、HTML形式のドキュメントが入っています。
The directory /usr/share/newlisp/modules contains modules with useful functions
POP3 mail, etc. The directory /usr/share/newlisp/guiserver contains sample programs
for writing GUI applications with newLISP-GS.
The directory /usr/share/doc/newlisp/ contains documentation in HTML format.
Win32 システムでは、全ファイルが、デフォルトの%PROGRAMFILES%\newlispディレクトリにインストールされます。
PROGRAMFILES は、英語版インストールでは、
C:\Program files\newlisp\ と解釈されるWin32 の環境変数です。
%PROGRAMFILES%\newlisp\modules と %PROGRAMFILES%\newlisp\guiserver のサブ・ディレクトリには、
外部ライブラリへのインタフェース用モジュールや newLISP-GS で書かれたサンプル・プログラムが入っています。
On Win32 systems, all files are installed in the default directory %PROGRAMFILES%\newlisp.
PROGRAMFILES is a Win32 environment variable that resolves to
C:\Program files\newlisp\ in English language installations. The subdirectories
%PROGRAMFILES%\newlisp\modules and %PROGRAMFILES%\newlisp\guiserver
contain modules for interfacing to external libraries and sample programs written for
newLISP-GS.
Unix や Win32 の多くの共有ライブラリは newLISP の機能を拡張するために使えます。
例えば、グラフィカル・ユーザ・インターフェイス用ライブラリや
暗号と復号用ライブラリ、データベース・アクセス用などがあります。
Many shared libraries on Unix and Win32 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 を使います。
導入したライブラリ関数への入出力用フォーマットを簡単に実現できる関数として、
pack、unpack、
get-string、
get-int、get-long
等があります。
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-string,
get-int and get-long exist
to facilitate formatting input and output to and from imported library functions.
Code Patterns in newLISP 文書の
23. Extending newLISP の章も見て下さい。
See also the chapter
23. Extending newLISP in the
Code Patterns in newLISP document.
newLISP を共有ライブラリのようにコンパイルすることができます。
Linux や BSD 、その他の Unix では、ライブラリを newlisp.so から呼び出します。
Windows では newlisp.dll となり、Mac OS X では newlisp.dylib です。
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 Mac OS X. A newLISP shared library is used like
any other shared library.
導入されるメインの関数は、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 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.
newlispEvalStr に複数行のソースを渡す際は、
その両端を [cmd], [/cmd] タグで囲うようにして下さい:
When passing multi-line source to newlispEvalStr, that
source should be bracketed by [cmd], [/cmd] tags,
each on a different line:
(set 'code [text][cmd] ... ... ... [/cmd][/text])
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 宣言文評価と 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.
最初に空行を入力することで、複数行の式を入力できます。
一旦、複数行モードに入れば、別の空行で入力モードに戻り、
入力された宣言文を評価します。
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:
>
(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 の内部で使われます。
[cmd] と [/cmd] のタグは、 newLISP-GS Java IDE でも、
使う必要があります。
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 controllling newLISP and internally by the
net-eval function. The [cmd] and [/cmd]
tags must also be used in the console part of the newLISP-GS Java IDE.
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 )は、
浮動小数点数を返します。
整数演算子は、浮動小数点数の小数を省いて整数に丸めます
(訳注:0 に近い整数に丸めるということ)。
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.
dotimes と for のループ変数は、
sequenceの結果と同じように、
それらの値に浮動小数点数を使っていることに注意して下さい。
Note that the looping variables in dotimes and
for, as well as the result of
sequence, use floating point numbers for their values.
整数を要求する関数を使うライブラリから
導入する時は、注意を払わなければなりません。
+, -, *, / を再定義した後では、
倍精度浮動小数点数が不用意に渡されるかもしれません。
この場合、浮動小数点数は、関数 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.
コマンドラインから、入力または編集された式を評価します。
複雑なプログラムは、タイプ中、対応する括弧を示すモードを持っている
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.
一行コメントは、; (semicolon) か # (number sign) で始まり、
行の終わりまで及びます。
# がスクリプトとシェルの一行コメントして共通に使える
Linux/Unix 環境でスクリプト言語として newLISP を使う時、
# が便利です。
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.
nil と true は、それ自身に評価されるブール・データ型です:
nil and true are Boolean data types that
evaluate to themselves:
nil → nil true → true
整数 と 浮動小数点 の数値は、それ自身に評価されます:
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
整数は、64 ビット数値です(符号ビットを含みます、バージョン 8.9.7 より前は、32 ビットです)。
有効整数は、-9,223,372,036,854,775,808 と +9,223,372,036,854,775,807 の間です。
浮動小数点数から変換される最大数は、二つの制限の内の一つに丸められます。
32ビット数値で制限される newLISP の内部整数(訳注:例えば、date-parse)は、
+2,147,483,647 か -2,147,483,648 のどちらかでオーバーフローします。
浮動小数点数は、IEEE 754 の 64 ビット倍精度です。
formatで特殊フォーマット文字を使えば、
符号無しで 18,446,744,073,709,551,615 まで、表示可能です。
Integers are 64-bit numbers (including the sign bit, 32-bit before version 8.9.7).
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. 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.
文字列 は、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 2048 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):
| character | description |
|---|---|
| \" | ダブル・クォートで囲まれた文字列内のダブル・クォート 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) |
| \t | タブ文字 (ASCII 9) for a TAB character (ASCII 9) |
| \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,048 文字数を超えることはできません。
それより長い文字列は、[text] と [/text] のタグの境界に使います。
newLISP は、2,048 文字以上の文字列出力にこれらのタグを自動的に使います。
Quoted strings cannot exceed 2,048 characters. Longer strings
should use the [text] and [/text] tag delimiters.
newLISP automatically uses these tags for string output longer than 2,048 characters.
{ (left curly bracket), } (right curly bracket),
と [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>
上記例で、< > (angle brackets) 間の数字は、
関数add の(マシン依存)16進数メモリ・アドレスです。
それは、組込 primitive を出力する時に表示されます。
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.
クォート式 は評価されると、一個の ' (single quote) を失います:
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 のように)リストの第一要素を、式の残りを評価する前に、評価して評価されます。
評価の結果は、リストの残りの要素に適用されますので、
ラムダ 式、ラムダ・マクロ 式、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 は、引数に適用する前に
式の functor (function object) 部分を評価します:
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 関数は、special forms と呼ばれます。
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 あるいは Win32 での !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 Win32 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 を押して下さい。
Win32 上では、(exit) とタイプするか、Ctrl-C です。
To exit the newLISP shell on Linux/Unix, press Ctrl-D; on Win32,
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.
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.
ラムダ式は、lambda list という list の一形態で、
その引数は、左から右、右から左へと連結可能です。
例えば、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 キーワードは、リスト中のシンボルではなく、
lambda list という リストの特殊 type の指定子であることに注意して下さい。
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.
newLISP では、nil と true は、
共にシンボルでブール値の偽(false)と真(true)を現します。
内容次第で、nil と true は異なる扱いを受けます。
次の例は、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 はシンボルです。
次の例では、nil と true は評価され、ブール値を現します:
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 では、nil と空リスト () は、他の Lisp のように同じではありません。
条件式、
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 実装は、head と tail の名前として car と cdr を を使っていました。
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.
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:
| function | description |
|---|---|
| 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 | 行列のスカラー演算を実行する 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 |
| setf | 参照アレイの内容を設定する sets contents of an array reference |
| slice | アレイの一部を返す returns a slice of an array |
| sort | アレイの要素をソートする sort the elements in an array |
| 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.
アレイ(または、アレイを含む変数)の書き出しには、
関数source か save を使って下さい。
アレイの書き出し時、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.
正方でないアレイは可能ですが、
source や save を使って書き出す時に、正方化されます。
関数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.
いくつかの関数は、
一個以上の int-index (integer index) で指定された
アレイやリストや文字列要素(文字)を取ります。
正のインデックスの候補は 0, 1, …, N-2, N-1 で、N はリストの要素数です。
int-index が負なら、数列は -N, -N+1, …, -2, -1 となります。
負のインデックスに N を足すと、正のインデックスになります。
関数で対応していなければ、N-1 を超えるインデックスや -N 以下のインデックスは、
リストやアレイの境界外(out-of-bounds)エラーを起こします。
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.
暗黙のインデックス機能は、リストとアレイの要素や文字列中の文字を取り出す
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"
インデックスは、リストでも供給されます。
この場合、暗黙のインデックス機能は
push, pop,
ref, ref-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
暗黙のインデックス機能は、
s式の関数オブジェクト(functor)位置において、newLISP の構文ルールを壊しませんが、
他のデータ型に対する既存のルールを拡張することに注意して下さい。
オリジナルの Lisp では、s式リストの第一要素が関数となり、残りの要素が引数として適用されます。
newLISP では、s式の関数オブジェクト(functor)位置にあるリストは、それに続くインデックス引数を使って、自己インデックス関数的に用いられます。
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.
デフォルト・ファンクタ は、
コンテキスト内でコンテキスト自体と同じ名前を持つ関数オブジェクト(functor)です。
The context default function の章を見て下さい。
デフォルト・ファンクタは、
リストを参照する機構として用意されている暗黙のインデックス機能と一緒に使われます。
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
この例では、aList は、MyList:MyList のコピーではなく、参照です。
コンテキストについての詳細情報は、
Programming with contexts を見て下さい。
In this example, aList references MyList:MyList,
not a copy of it. For more information about contexts, see
Programming with 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)
rest や slice の暗黙の形式は、
リストに先行し、オフセットと長さを表す一つないし二つの数値で形成されます。
長さが負数なら、リストや文字列の終端から数えます(訳注:-1 が終端):
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) (set 'str "abcdefg") (1 str) → "bcdefg" (2 str) → "cdefg" (2 3 str) → "cde" (-3 2 str) → "ef" (2 -2 str) → "cde"
UTF-8版 newLISP で、関数 rest、first、last は、マルチバイト境界で作用します。
しかし、rest や slice の暗黙のインデックス機能形式は、
常に、1バイト境界で作用し、バイナリ・データに使えます。
正規表現関数 find と regex からのオフセットと長さの結果もまた、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.
インデックスで参照されるリスト、アレイ、文字列の部分は、
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"
全要素か、入れ子のリストかアレイは、この方法で変更できます。
暗黙の rest や slice を使った
リストやアレイの部分(訳注:要素でなく、部分リストか部分アレイ)は、
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-chracacter string.
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:
| function | description |
|---|---|
| ++ | 整数モードで数値を加算する 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 |
| inc | 変数、リスト、アレイで参照される数値を加算する increments a number referenced by a variable, list or array |
| 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 |
いくつかの破壊的関数は、
目標オブジェクトを関数 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.
以下のことは、ループや begin 式内のフロー制御を中断する方法です。
What follows are methods of interrupting the control flow inside both
loops and the begin expression.
ループ機能 dolist、、dotimes は、
ループ早期脱出のためのオプション条件を取ることができます。
さらに、catch と throw は、
ループ本体からの脱出し、他の形式または制御ブロックに適応可能な汎用形式です。
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.
newLISP 関数型言語なので、関数や繰り返しからの脱出に
break や return 宣言文を使いません。
代わりに、catch と throw の機能を使って、
関数や繰り返しのいかなる場所からも脱出できます:
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 が真なら、x が catch 式から戻り、
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.
論理関数 and と or を使って、
宣言文ブロックを、内包する関数のブール代数の結果次第で、脱出するように組み立てられます:
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 ().
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) が呼ばれ、x は 0 に束縛され、
(g 0) が実行中、x は (f) によって 0 と報告されます。
(g 0) の実行後、(f) の呼出しは、再び、x を 1 として報告します。
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 は、レキシカル・スコープの違った形式でコンテキストを使います。
詳細な情報は、default functors と同様に
Contexts と
Programming with contexts の章を見て下さい。
newLISP uses contexts for different forms of lexical scoping. See the
chapters Contexts and
Programming with contexts, as well as
the section default functors for more information.
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 can also be copied and dynamically assigned to variables or passed as arguments.
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 コンテキストは、コンテキス名であると同時に、
組込関数や true と nil のような特殊シンボルを持っています。
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)
次の規則は、
作成したシンボルがどのコンテキストに割り当てるられるかを明確にすることで、
コンテキストへの理解を簡単にします。
The following rules should simplify the process of understanding contexts by
identifying to which context the created symbols are being assigned.
newLISP は、トップ・レベルの式を解析し、翻訳します。
この解析中にシンボルを生成します。式が翻訳された後、それは評価を得ます。
newLISP first parses and translates each top level expression. The symbols
are created during this phase. After the expression is translated, it gets
evaluated.
関数load、sym、eval-string が呼ばれた時、newLISP は、シンボルを最初に見つけた時、生成します。
newLISP がソースを読み込む時は、評価が起こる 前 に、シンボルが生成されます。
A symbol is created when newLISP first sees it, when calling the
load, sym,
or eval-string functions. When newLISP reads
a source file, symbols are created before evaluation occurs.
コード翻訳中に、見知らぬシンボルに出会うと、
その定義の検索が現在のコンテキスト内で始まります。それに失敗すると、
検索は、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.
いったんシンボルが、生成され、特定のコンテキストに割り当てられると、
それは、そのコンテキストに恒久的に従属します。
Once a symbol is created and assigned to a specific context,
it will belong to that context permanently.
ユーザ定義関数が評価される時、コンテキストは、
それが呼ばれたシンボルの親のコンテキストに切り替わります。
When a user-defined function is evaluated, the context is switched to the parent
context of the symbol it is called with.
コンテキスは、関数 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 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, existing contexts like MAIN do not require quoting.
newLISP 上記コードを読み込む時、最初の宣言文 (context 'FOO) が評価されます。
これは、newLISP に FOO への名前空間切り替えを起こさせ、残りの式を読み込み評価する時、
続くシンボル、var, x, y, z が全て、
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.
名前空間FOOの外側のどこからか var や func を参照するには、
コンテキスト名の先付けが必要です:
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)
関数 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)
コンテキストは、まだ存在していないものが参照された時、暗黙に生成されます。
関数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 のパーツです。
シンボル x と y は、まだ MAIN のパーツです。
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.
コマンドラインで 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 newLISP where 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-triangle と draw-circle は
— それらのパラメータ x, y, z を伴って — 、
コンテキスト 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 different context name (= 'A:val 'B:val) → nil (= (term 'A:val) (term 'B:val)) → true
注記:シンボルの内容ではなくシンボル自身に対象にしているので、
シンボルを ' (single quote) でクォートしています。
Note: The symbols are quoted with a ' (single quote) because we are interested in
the symbol i
デフォルトで、組込関数と nil や true のようなシンボルのみが、
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 宣言文なしでは、
二番目の aVar は 123 の代わりに nil を返すでしょう。
FOO が前もって定義されたシンボル(この例では、aVar)を持っているなら、
代わりに — グローバルのでなく — その シンボル(訳注:FOO:aVar)の値が返ります。
MAIN コンテキストからシンボルをグローバルにすることができることに注意して下さい
(訳注:関数global は MAIN 上でしか使えないということ)。
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.
関数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.
グローバルと組込関数のシンボルに、あるコンテキスト内で
それら 自身 のコンテキスト・シンボルを先付けすることにより、
上書きできます:
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 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 switch
contexts or use contexts which do not exist yet:
(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:
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.
コンテキストを生成あるいはロードするシーケンスは、予期しない結果につながることがあります。
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 がグローバル・プロテクト・シンボルとして、
すでに存在していて、正常にプロテクトのフラグがセットされています。
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.
それでも、コンテキスト ABC で FOO をローカル変数として使用することは、
ABC:FOO という風に先付けを明示することで可能です。
FOO could still be used as a local variable in the ABC
context by explicitly prefixing it, as in ABC:FOO.
大規模なアプリケーションを構築するモジュールとして使われるコンテキストを
ロードする時の予期しない振る舞いを避けるために、次のパターンを適用できます:
The following pattern can be applied to avoid unexpected behavior when
loading contexts being used as modules to build larger applications:
;; begin of file - MyModule.lsp (load "This.lsp") (load "That.lsp") (load "Other.lsp") (context 'MyModule) … (define (func x y z) (…)) … (context 'MAIN) (MyModule:func 1 2 3) (exit) ;; end of file
常に、モジュールの context 宣言文の 前に 、 コンテキストで必要とするモジュールをロードしておきます。 常に、モジュールの関数と値を安全にアクセルできる MAIN コンテキストに戻ってから終了します。
Always load the modules required by a context before the module's context statement. Always finish by switching back to the MAIN context, where the module's functions and values can be safely accessed.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.
ベストなプログラミング習慣は、1ファイルが1モジュールを含み、
ファイル名が使っているコンテキスト名と同じでなくとも、似ていることです:
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 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)
これについての詳細は、Serializing contexts の章を読んで下さい。
Read more about this in the section Serializing contexts.
モジュール・ファイルは、関数load を使ってロードされます。
プログラミング・プロジェクトがお互いに参照する多数のモジュールからなるなら、
コンテキストをロードする前に起こり得るコンテキストの前方参照による問題を避けるために、
コンテキストを予約宣言するべきです。
Module files are loaded using the load function.
If a programming project contains numerous modules that refer
to each other, they should 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.
目標コンテキストを最後のオプションにしている load 宣言文の時を除いて、
コンテキスト切り替えで始まっていないモジュールは、常に MAIN にロードされます。
関数load は、リモート位置から HTTP 経由で
モジュールをロードするために 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.
シリアライズすることは、
ソフトウェア・オブジェクトをファイルやメモリ内の文字列にセーブされる
文字ストリームに置き換えることで、持続性 をもたらします。
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).
デフォルト・ファンクタ またはデフォルト・ファンクション は、
その名前空間と同じ名前を持つシンボルかユーザ定義関数かマクロです。
コンテキストを関数の名前として使う時、または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.
ラムダ関数やラムダ・マクロのように、デフォルト・ファンクションを
map や apply で使うことができます。
Like a lambda or lambda-macro function, default functions can be used
with map or apply.
デフォルト・ファンクションは、
その名前空間内にあるレキシカルに隔離された静的変数をアップデートできます:
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 の中に置かれます。
上記例では、変数 x は、まだ MAIN の部品です。
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.
名前空間 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 an alternative use (new Tree 'MyHash) ; create from built-in template
どちらの方法も、MyHash の辞書空間とデフォルト・ファンクタを作るのに使えます。
キー・値ペアの生成と値の呼び出しは簡単です:
Either method can be used to make the MyHash dictionary space and default
functor. Creating key-value pairs and retrieving a value is easy:
(Myhash "var" 123) ; create and set variable/value pair
(Myhash "var") ; → 123 ; retrieve value
デフォルト・ファンクタ には、nil 以外のいかなる値も入れてはいけないことに注意して下さい。デフォルト・ファンクタは、文字列からシンボルを生成し、値が指定されていれば、それを設定する辞書ハッシュ関数のように動作します。
Note that the default functor should not be initialized to any
value other than nil. The default functor works like a dictionary
hash function creating the symbols in the string following it and setting it
to the value if specified.
この方法で作られたシンボル変数は、スペースや通常 newLISP のシンボル名としては許可されない文字を含むことが可能です:
Symbol variables created this way can contain spaces or other characters
normally not allowed in newLISP symbol names:
(define Foo: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
エントリをにセットすることは、実際、名前空間からそれを削除します。
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)))
辞書へのエントリは、リストからでも可能です:
Entries in the dictionary can also be created from a list:
(Foo '(("#1234" "hello world") ("John Doe" 123) ("var" (a b c d))) → Foo
リストは、ソートされたキー->値ペアとして、繰り返し操作が可能です:
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)
多くの組込関数のように、ハッシュ式はその内容の直接変更可能な参照を返します:
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 上からロードする際、必要となる set や sym でデフォルトのシンボルが上書きされるのを予防します。
次の違いに注意してください:
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 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.
デフォルト・ファンクタ は、データの保持にも使えます。
このデータがリストか文字列なら、コンテキスト名をデータへの参照として使えます:
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 パラメータを 値のコピー で渡します。
これは、大きなリストや文字列をユーザ定義関数やマクロに渡す際、
潜在的な問題を引き起こします。
デフォルト・ファンクタを使って名前空間にまとめられた(packed)文字列やリストは、
自動的に参照で渡されます:
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).
関数的オブジェクト指向プログラミング (FOOP) は、次の五つの原理に基づいています:
Functional-object oriented programming (FOOP) is based on the following
five principles:
クラスの属性とメソッドは、オブジェクトクラスの名前空間に保存されている。
Class attributes and methods are stored in the namespace of the object class.
名前空間のデフォルト・ファンクタは、オブジェクト・コンストラクタ・メソッドを保持する。
The namespace default functor holds the object constructor method.
オブジェクトのクラスを表すコンテキスト・シンボルを第一要素に持つリストを使って、オブジェクトを構成する。
An object is constructed using a list, the first element of which is the
context symbol describing the class of the object.
オブジェクトから特定のクラスを選択する
: (colon) オペレータを使って多態性を実装する。
Polymorphism is implemented using the : (colon)
operator, which selects the appropriate class from the object.
関数self でクラス・メソッド関数内の目的オブジェクトをアクセスする。
A target object inside a class-method function is accessed via the self
function.
以下の文節は、 neglook.com の Michael Michaels の企画による FOOP についての 短い入門書です。
The following paragraphs are a short introduction to FOOP as designed by
Michael Michaels from neglook.com.
クラスの属性とメソッドは、オブジェクト・クラスの名前空間に保存されます。
オブジェクトの実体データは、この名前空間/コンテキストには、保存されません。
クラス名前空間でのデータ変数は、オブジェクト特有の情報を含まない完全体として、
オブジェクトのクラスにのみ記述します。
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.
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)
生成されたオブジェクトは、それを生成するのに必要な関数と同一です (hence 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 宣言文の Address や Street に、
クォートを付ける必要がないことに注意して下さい。
データを割り付けるための 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.
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:area と circle:area というように、
異なる名前空間に属しているだけです。
ローカル・パラメータ p, c, dx, dy は、
全て 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))
area や move シンボルに : (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)
この例では、正しく特定されたシンボルが構築され、
コロンに続くシンボルとコンテキスト名(オブジェクト・リストの第一要素)に基づくオブジェクト・データに適用されます。
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.
前述の全ての例で、クラス関数は 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.
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.
newLISP は、並列処理を搭載し制御する
Cilk-ライクな API を実装しています。
API は、マルチコア・コンピュータ・アーキテクチャの利点を活かすことができます。
マルチ・プロセスを開始し、同期状態での結果を収集するのには、
三つの関数 spawn、sync、abort
だけが必要です。
オペレーティングシステムは、CPU 内の異なるコアにプロセスを分散し、
十分なコアがないなら、同一コアで並列にそれらを実行します。
newLISP は API を実装しているだけで、子プロセスとして呼び出された(spawned)手続きのスケジュールの最適化は、 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 以来、send と receive の
メッセージ関数は、親プロセスと子プロセス間の通信に利用可能です。
ブロッキングとノン・ブロッキング通信に関数を使うことができ、
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.
内部的には、
プロセスや計算結果の共有メモリを通した受け渡しの同期を制御する
ロー・レベル関数 fork,
wait-pid,
destroy,
share を newLISP は使います。
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.
Mac OS X や他の Unix が上でのみ、Cilk API は、タスクを並列化します。
Win32 では、API 群は、Unix の振る舞いをシミュレートしますが、
タスクを(訳注:並列ではなく)逐次実行します。
この方法により、全てのプラットフォームで走るコードを書く事ができます。
Only on Mac OS X and other Unixes will the Cilk API parallelize tasks.
On Win32, the API partly simulates the behavior on Unix but executes tasks
sequentially. This way, code can be written that runs on all platforms.
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-file、
write-file、
append-file、
delete-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.
XML-エンコード・データまたはドキュメントの newLISP の組込サポートは、
三つの関数:
xml-parse、
xml-type-tags、
xml-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 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>
(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-tags と
xml-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:
(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.
マニュアルのリファレンス項の
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に
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:
| method | description |
|---|---|
| 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-enc と base64-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.
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.
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.
多くの国々が、十進数の区切りにピリオドでなくカンマを使っています。
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 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.
多くのヨーロッパの言語にとっては、
内部的に各文字が一バイト で表示されている限り
非 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.
Mac OS X バイナリ・インストーラには、
デフォルトで、UTF-8 版が入っています。
The Mac OS X 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 可能にして下さい。
Linux/Unix で、Tcl/Tk フロント・エンドを使っている時、
Unix 環境変数が正しく設定されている限り、
Tcl/Tk は、自動的に UTF-8 表示に切り替えます。
WinXP の notepad.exe の U.S. バージョンは、
Unicode UTF-8 エンコード文字を表示できますが、
コマンド・シェルとTcl/Tk フロント・エンドはできません。
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.
When using the Tcl/Tk front-end on Linux/Unix,
Tcl/Tk will automatically switch to UTF-8 display
as long as the Unix environment variable
is set correctly.
The U.S. version of WinXP's notepad.exe
can display Unicode UTF-8–encoded characters,
but the command shell and the Tcl/Tk front-end 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.
UTF-8 版 newLISP が使える時、
次の文字列関数が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:
| function | description |
|---|---|
| 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ビット・バイト上で動作します。
find や regex で位置が返る時、
それらは、マルチ・バイトの文字位置ではなく、1バイト単位の位置です。
関数get-char と slice は、
UTF-8 版 newLISP であっても
マルチ・バイト文字のオフセットを取らず、1バイト単位のオフセットです。
関数reverse は、
文字ベクターではなくバイト・ベクターで逆転します。
UTF-8 版 newLISP では、最後の三つの関数をバイナリの非テキストデータの
操作に使えます。
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.
directory, find,
member, parse, regex,
regex-comp, replace で使われる—
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.
| function | description |
|---|---|
| unicode | converts UTF-8 or ASCII strings into USC-4 Unicode |
| utf8 | converts UCS-4 Unicode strings to UTF-8 |
| utf8len | returns the number of UTF-8 characters in a 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.
いくつかの例題プログラムは、
パラメータを二つのグループに分けるカンマを使っている関数を含んでいます。
これは、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 …)
(…))
この関数が呼ばれた時、a、b、c だけが、パラメータとして使われます。
他 (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.
環境変数を宣言し、初期化する他の方法については、
let、letex、
letn を見て下さい。
For other ways of declaring and initializing local variables,
see let, letex and
letn.
MS Windows では、
link.lsp を使ってソース・コードと newLISP 実行部を一緒に結合し、
自己完結アプリケーションを構築できます。
UNIX では、結合された実行部はフル・パス名で呼び出された時にのみ、正しく動作します。
On MS Windows, source code and the newLISP executable can be linked together
to build a self-contained application by using link.lsp. On UNIX, the
new linked executable will only work correctly when called with the full pathname.
link.lsp プログラムは、配布ソースの newlisp/util ディレクトリにあります。
一例として、次のコードを newLISP 実行部に結合して、
簡単な自己完結アプケーションの形にしています:
The link.lsp program is located in the newlisp/util directory
of the source distributions. As an example, the following code is linked to the
newLISP executable to form a simple, self-contained application:
;; uppercase.lsp - Link example (println (upper-case (main-args 1))) (exit)
ファイル uppercase.lsp にあるこのプログラムは、
コマンドライン上の最初の単語を取り、それを大文字に変換します。
This program, which resides in the file 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 four steps:
(1) 次のファイルを同じ現行ディレクトリに置きます:
Put the following files into the same, current directory:
(a) newLISP 実行部、newlisp(または Win32 用 newlisp.exe のコピー)
a copy of the newLISP executable, either newlisp (or newlisp.exe on Win32);
(b) newlisp.exe
newlisp.exe;
(c) link.lsp
link.lsp; and
(d) 結合するプログラム (この例では、uppercase.lsp)
the program to link with (uppercase.lsp in this example).
(2) シェル上で、ステップ1を参照するディレクトリに移動し、
link.lsp を(訳注:newLISP に)ロードします:
In a shell, go to the directory referred to in step 1
and load link.lsp:
newlisp link.lsp
(3) newLISP シェルで、次のいずれかをタイプします:
In the newLISP shell, type one of the following:
(link "newlisp.exe" "uppercase.exe" "uppercase.lsp") ; Win32
(4) newLISP シェルから抜けて、次のようにタイプします:
Exit the newLISP shell and type:
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.
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.
次の規則が、変数や関数に使われるシンボルの命名に適用されます:
The following rules apply to the naming of symbols
used as variables or functions:
次のシンボルは全て、newLISP では、適正なシンボル名です:
All of the following symbols are legal variable names in newLISP:
myvar A-name X34-zz [* 7 5 ()};] *111*
時には、newLISP の変数では不適切な文字を含むキーを持つ
ハッシュ・ライクの検索辞書を生成することが、
役に立ちます。
関数 sym と context は、
これらの文字を含むシンボルの生成に使えます:
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 (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.
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
十六進数 は、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.
0xFF → 255 0x10ab → 4267 0X10CC → 4300
二進数 は0b (または 0B) で始まり、64個まで 1 か 0 が 続きます。それ以外の文字は二進数の終わりを意味します。
Binaries start with a 0b (or 0B),
followed by up to 64 1's or 0s. Any other character ends the binary number.
0b101010 → 42
八進数 は、オプションの + (plus) か - (minus) 符号と
0 (zero) から始まり、八進数字 01234567 の組み合わせが続きます。
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.
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.
1.23 → 1.23 -1.23 → -1.23 +2.3456 → 2.3456 .506 → 0.506
下記のように、指数表記(または、科学的表記)は、
仮数部 (または、仮数) と呼ばれる浮動小数点数から始まり、
文字 e か E と整数の指数部 が続きます。
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
関数パラメータの型と名前の表記には、
次の命名則がリファレンス・セクションを通して適用されます:
To describe the types and names of a function's parameters,
the following naming convention is used throughout the reference section:
引数は、引数の型と名前を - (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 で作成された)アレイ。
An array (constructed with the array function).
評価するための一個以上の式。
一個より多い式は、連続して評価されます。
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
true か nil、または、この二つのどちらかに評価される式。
true, nil, or an expression evaluating to one of these two.
true, nil, (<= X 10)
コンテキスト(名前空間)または、コンテキストを保持する変数シンボルに評価される式。
An expression evaluating to a context (namespace) or a variable symbol
holding a context.
MyContext, aCtx, TheCTX
この章に表記されているあらゆるデータ型。
Any data type described in this chapter.
シンボルまたは、演算子かラムダ式に評価される式。
A symbol or an expression evaluating to
an operator symbol or lambda expression.
+, add, (first '(add sub)), (lambda (x) (+ x x))
整数または、整数に評価される式。
一般に、整数が予想される時に浮動小数点数が使われた場合、
値は整数に切り捨てられます。
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)
(あらゆる型の)要素のリストまたは、リストに評価される式。
A list of elements (any type)
or an expression evaluating to a list.
(a b c "hello" (+ 3 4))
整数か浮動小数点数、または、このどちらかに評価される式。
整数が渡された場合は、
浮動小数点数に変換されます。
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)
各行の要素がリストのリスト、または、各行の要素がアレイのアレイ。
全ての(行の)要素リストまたはアレイは、同じ長さです。
どのようなような型も行列の要素にできますが、
det、
multiply、
invert
のような行列専用操作を使う時は、
すべての数値は、浮動小数点数か整数であることが必要です。
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.
行列の次元は、
行の数と行当たりの列の数を指し示すことで定義されます。
行列で動作する関数は、行中の余計な列を無視します。
見つからない行の要素には、
関数det、
multiply、
invert では 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
シンボルによって参照される位置、または、
リストやアレイで定義される位置、または、
nth や implicit indexing で
指し示される文字列、または、
first、
last、
assoc、
lookup のような関数で参照される位置。
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.
文字列、または、文字列に評価される式。
A string or an expression that evaluates to a string.
"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:
| character | description |
|---|---|
| \" | ダブル・クォートで囲まれた文字列内のダブル・クォート 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) |
| \t | タブ文字 (ASCII 9) the tab character (ASCII 9) |
| \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 |
| \unnnn | 4 つの 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.
シンボル、または、シンボルに評価される式。
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.
シンボル、存在するコンテキスト、または、
コンテキストが生成されるシンボルに評価される式。
コンテキストが存在していない場合は、
多くの関数は、無条件にそれらを生成します
(例えば、bayes-train、
context、
eval-string、
load、
sym、
xml-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.
いくつかの関数は、複数のグループに現れます。
Some functions appear in more than one group.
| +, -, *, /, % | 整数演算 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 |
| 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 |
| 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 |
| lookup | 連想リスト中のメンバーを調べる looks up members in an association list |
| map | リストの要素に関数を適用し、その結果を集める maps a function over members of a list, collecting the results |
| match | リストに対してパターン・マッチングする。文字列に対しては、find と regex を参照 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 |
| address | 数値か文字列のメモリ・アドレスを取得する gets the memory address of a number or string |
| append | リスト、アレイ、文字列を結合し、新しいリスト、アレイ、文字列を形成する appends lists, arrays or strings to form a new list, array or string |
| 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 |
| 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 | x の y 乗を計算する 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 |
| 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) |
| 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 |
| 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 shift left, bit shift right |
| & | ビット単位の論理積 bitwise and |
| | | ビット単位の論理和 bitwise inclusive or |
| ^ | ビット単位の排他的論理和 bitwise exclusive or |
| ~ | ビット単位の論理否定 bitwise not |
(訳注:述語の意味は、こちらをどうぞ。)
| atom? | アトムのチェック checks if an expression is an atom |
| array? | アレイのチェック checks if an expression is an array |
| 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 | 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 |
| amb | 引数からランダムに選択し、それを評価する randomly selects an argument and evaluates it |
| bayes-query | データ・セットのベイズ確率を計算する calculates Bayesian probabilities for a data set |
| bayes-train | Bayesian か頻度解析のリストで要素を数える 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 |
| 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 検定を行なう performs a t-test on dependent or independent data samples |
| 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 |
| 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 |
| 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 |
| コンソールかデバイスに出力する 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 |
| 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 |
| ! | オペレーティング・システムのシェルに出る shells out to the operating system |
| abort | spawn で開始した子プロセスを中断する aborts a child process started with spawn |
| destroy | fork か process で生成したプロセスを破棄する 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 |
| 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 |
| 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 |
| 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 |
| 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 | 通信用ローカル・ソケットを待ち受ける 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 |
(訳注:Reflection については、こちらを参照して下さい。)
| command-event | コマンドラインや HTTP リスクエストを前処理する pre-processes the command-line and HTTP requests |
| error-event | エラー・ハンドラを定義する defines an error handler |
| last-error | エラー番号とテキストを報告する report the last error number and text |
| 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 |
| $ | システム変数 $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 文字
(訳注: print、
save、
source 時の整形文字)を変更する 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 |
| 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 |
| 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 |
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 を使えば、
標準出力を取得したり、標準入力を与えることができます。
関数process は、ノン・ブロッキングの子プロセスを起動し、
標準 I/O や標準エラーをパイプへリダイレクトできます。
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
用に定義されたプロセス生成フラグを取ります。このパラメータの含めることは、
コマンド・シェル・ウィンドウ無しの異なるプロセス生成を強います。
このパラメータは、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.
! (exclamation mark) は、括弧や ! に続くスペースを省略して、
コマンド・ラインのシェル・オペレータとしても使えることに注意して下さい:
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.
正規表現を使う関数 (directory、
ends-with、
find、
parse、
regex、
search、
starts-with、
replace) は全て、
関数の実行中もしくは実行後に、
その結果をシステム変数として予約された
$0、
$1、
$2–$15 に束縛します。
システム変数は、他のシンボルと同様に扱えます。
選択肢の一つとして、これらの変数の内容を
($ 0)、($ 1)、
($ 2) 等を使ってアクセスできます。
この方法では、インデックス操作が許されています。
(例えば、($ i)、ここで、i は整数)。
The functions that use regular expressions (directory,
ends-with, find, 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"
int-1 から続く全ての数値の和を返します。
Returns the sum of all numbers in int-1 —.
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.
int-1 から int-i までを掛け算します。
The product is calculated for int-1 to int-i.
リストの終わりに達するまで、次々と割り算して行きます。
ゼロで割るとエラーを起こします。
Each result is divided successively until the end of the list is reached.
Division by zero causes an error.
次(訳注:右隣)の 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 (zero) に近い整数に丸められます。
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 (zero) として扱われます。
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 >)
++ 演算子は、
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.
-- 演算子は、
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.
式は評価され、その結果が続けて比較されます。
比較した結果が、比較演算子に一致する間は、
全ての引数が試されるまで、評価と比較が続けられ、
結果は、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 numer 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)
数値 int-1 は int-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.
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
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
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
int の数値に対して、
ビット単位の not 演算を行い、全てのビットを反転します。
A bitwise not operation is performed
on the number in int,
reversing all of the bits.
(format "%X" (~ 0xFFFFFFAA)) → "55" (~ 0xFFFFFFFF) → 0
コロンは名前空間のコンテキストとシンボル名を
別けるためだけに使われるのではなく、
演算子としても使われます。
演算子として使う時、コロン : は、
オブジェクト・リストのコンテキスト名からくるコンテキスト・シンボルと
コロンに続くシンボルを組み立てます。
list-object のオブジェクト・リストは、
他のパラメータを続けることができます。
The colon is used not only as a syntactic separator between
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.
演算子: は、
コンテキスト(名前空間)によって表される
異なるオブジェクト・クラスの部品となるオブジェクト・
メソッドの
多態性(polymorphism)
を実装します。
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 は、現在の
親プロセスが与えた int-pid のプロセスID
で特定される子プロセスを中断します。
プロセスは、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.
関数 abort は、Win32では利用できません。
The function abort is not available on Win32.
(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.
num の数値の絶対値を返します。
Returns the absolute value of the number in num.
(abs -3.5) → 3.5
num-radians の値の逆余弦関数を計算します。
The arc-cosine function is calculated
from the number in num-radians.
(acos 1) → 0 (cos (acos 1)) → 1
num-radians の逆双曲線余弦関数を計算します。
ここで、num-radians は、双曲線余弦関数値です。
num-radians が 1 より小さい時、
acosh は、NaN を返します。
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
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
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-char、
get-int、
get-long、
get-float も見て下さい。
See also the get-char, get-int,
get-long and get-float functions.
式 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 と同じ関数を使います。
ランダムな浮動小数点数の生成には、
random、
randomize、
normal を使って下さい。
特定の開始ポイントで擬似乱数生成プロセスを初期化するには、
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.
式 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 は、リストに作用し、
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 of 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.
変更を目的とする既存のリストや文字列の結合には(訳注:つまり、副作用が必要な時)、
関数 extend と push を使って下さい。
Use the functions extend and push
to append to an existing list or string modifying the target.
write-file のように動作しますが、
str-filename のファイルが存在する時は、
str-buffer の内容を追加します。
ファイルが存在しない時は、それを作ります(この場合、
append-file は、write-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-name に、
http:// や 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.com で
str-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-file と
write-file も参照して下さい。
See also read-file and
write-file.
func(組込関数、ユーザ定義関数、ラムダ式)の内容を
list を引数にして適用します。
(訳注:引数の list の括弧を外して、func に与える)
Applies the contents of func
(primitive, user-defined function, or lambda expression)
to the arguments in list.
(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_ (args) 2))
(my-gcd 12 18 6) → 6
(my-gcd 12 18 6 4) → 2
最後の例は、apply の畳み込み(reduce) が、
二引数関数を一度に複数の引数を取れるようにする方法を示しています。
組込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 は、
dotimes や case のような
引数の中のいくつかだけが評価されるような特殊な形式 を持つものではなく、
引数を全て評価する関数や演算子に対して使うべきです。
そうしないと、失敗します。
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 では、 or や and を apply できませんが、 newLISP では、使えます。)> (apply or '(nil nil 1)) 1 > (apply and '(1 2 3)) 3 >)
評価中の 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)
最初の例では、
引数が二つの局所変数 a と b に束縛されるので、
空のリストが返ります。
二番目の例は、(最初の例と同様に)最初の二つの引数が束縛され、
三つの引数が残り、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.
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 のアレイは、大規模リストのランダム・インデクシングにおいて
あまりに遅くなる時には、いつでも使うべきです。
全てのリスト関数がアレイに使えるわけではありません。
詳細は、arrays の章を見て下さい。
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 (myarray 0 -1) → 4 ;; use implicit indexing and slicing on arrays (myarray 1) → (a b c d) (myarray 0 -1) → 4 (2 myarray) → (c d) (-3 2 myarray) → (b c)
行全体を置き換える際は、アレイを使ってすることに注意して下さい。
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
関数source や save を使って、
アレイを記述する時に生成されるコードには、
それを生成するのに必要な 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 から変換されたリストを返します
オリジナルのアレイは、変わりません:
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)
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
num-radians の数値の逆正弦関数を計算し、
結果を返します。
Calculates the arcsine function from the number in num-radians
and returns the result.
(asin 1) → 1.570796327 (sin (asin 1)) → 1
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
第一構文では、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
setf と一緒の assoc は、
連想の変更に使えます。
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"
連想リストで置換するには、
関数 assoc と共に setf を使います。
関数 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.
num-radians の逆正接が
計算され、返ります。
The arctangent of num-radians
is calculated and returned.
(atan 1) → 0.7853981634 (tan (atan 1)) → 1
関数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
num-radians の逆双曲線正接を計算します。
ここで、num-radians は、双曲線正接値です。
もし、num-radians の絶対値が、1 より大きいなら、
atanh は NaN を返します。
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
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
str の BASE64 文字列をデコードします。
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.
str の文字列は、BASE64 フォーマットにエンコードされます。
このフォーマットは、3 * 8 = 24 の入力ビット列を 4 * 8 = 32 出力ビット列にエンコードします。
出力ビット列の各8ビットは、入力文字列からの6ビットに相当します。
この6ビットは、文字 A–Z と a–z 数字 0–9
そして、キャラクタ + (plus sign) と / (slash) からなる 64語にエンコードされます。
= (equals sign) は、置き換えで使われなかった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-flag が true に評価されると、
空文字列 "" は "" になります。
どちらの変換物も base64-dec でデコードすると、
"" になります。
Without the optional bool-flag parameter the empty string "" is
encoded into "====". If bool-flag evaluates to true, the
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.
(訳注:訳者は、この手の事情に疎いので、
ベイズの定理、
ベイズ推定、
ベイズ確率、
マルコフ連鎖、
等をご一読の上、原文をお読み頂くことを強くお薦めします。)
トークン(以下単語と記す)リスト(list-L)と学習辞書(context-D)を取り、
一つのカテゴリ(A or Mc)における単語と
他のすべてのカテゴリ(Mi)に対する1カテゴリ(B)
との結合確率のリストを返します。
list-L の全ての単語は、context-D に見出されるべきです。
デフォルトの R.A. Fisher Chi² モードを使う時、
存在しない単語は、全てのカテゴリでの等確率へ結果を歪曲するでしょう。
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)
against all other categories (Mi).
All tokens in list-L
should occur in context-D.
When using the default R.A. Fisher Chi² mode,
nonexistent tokens will skew results
toward equal probability in all categories.
存在しない単語は、
bool-chain を true にして
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.
bool-probs に指定されたフラグ次第で、
bayes-query は、
確率を合成する
R. A. Fisher カイ二乗法か
Chain Bayesian 法のどちらかを使います。
デフォルトは、bool-probsにフラグ無しか nil の時で、
確率を合成するカイ二乗法が使われます。
bool-probs が true の時は、
Chain Bayesian 法が使われます。
Depending on the flag specified in bool-probs,
bayes-query employs either the
R. A. Fisher Chi² method of compounding probabilities
or the Chain Bayesian method.
By default, when no flag or nil is specified in bool-probs,
the Chi² method of compounding probabilities is used.
When specifying true in bool-probs,
the Chain Bayesian method is used.
R. A. Fisher カイ二乗法が使われるなら、
異なる学習セットのカテゴリのトークンの全数は、
同じか、少なくあるべきです。
カテゴリ中の頻度が不均衡なら、結果は歪曲されるでしょう。
If the R.A. Fisher 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.
A と B の二つのカテゴリでは、
bayes-query は、次の公式を使います:
For two categories A and B,
bayes-query uses the following formula:
N カテゴリなら、
この公式を使います:
For N categories,
this formula is used:
確率(p(B) と一緒の p(Mi) または p(A))は、
Bayesian 事前確率を表します。
p(Mc|tkn) と p(A|tkn) は、
カテゴリやモデルの Bayesian 事後確率です。
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.
事前確率は、R. A. Fisher カイ二乗法か Chain Bayesian 法で
処理法が異なります。
Chain Bayesian 法では、
一単語計算からの事後確率は、
次の計算の事前確率を得ます。
R. A. Fisher カイ二乗法では、
事前確率は、連鎖して伝えられませんが、
確率は、カイ二乗法を使って合成されます。
Priors are handled differently,
depending on whether the R.A. Fisher 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 R.A. Fisher method,
priors are not passed on via chaining,
but probabilities are compounded using the Chi² method.
Chain Bayes モードでは、
一カテゴリのゼロ頻度の単語は、
カテゴリの確率を事実上 0 (zero)にします。
これはまた、結果に、全ての事後や事前の 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.
デフォルトの R.A. Fisher カイ二乗法は、
0 頻度に、敏感ではありませんし、
まだ、その単語の低確率を持続します。
これは、Bayesian 統計を使う自然言語処理では、重要な特徴です。
五つの異なる言語の集大成のカテゴリが、学習されているけれど、
一カテゴリのいくつかの単語が、他に存在しないことを考えて下さい。
純粋な Chain Bayesian 法が使われる時、
文章は、その正しいカテゴリに分類されません。
なぜなら、ちょうど一つの単語のゼロ・カウントが、
その所属するカテゴリへの分類を事実上、拒むからです。
The default R.A. Fisher 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 の戻り値は、各カテゴリの一つの確率値のリストです。
次に二つの事例を示します:
最初はデフォルト R.A. Fisher モード、
二つ目は 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 R.A. Fisher mode, the second for a data set processed with the
Chain Bayesian method.
バージョン 10.3.0 以前では、Fisher Chi² モードで返される確率値のリストは、全リスト和で各値を割った正規化がされていました。この正規化は、バージョン 10.3.0 でなくなりました。
Previous to version 10.3.0 the list of probability values returned
in Fisher Chi² mode was normalized by dividing each value by the sum of
the whole list. This normalization has been dropped in version 10.3.0.
次の例では、
二つのデータ・セットは、グーテンベル・グプロジェクト
(訳注;日本でいう青空文庫に相当?)の本です。
私たちは、違う作家は、ある単語を使う頻度が異なると推測し、
文章が、一方の作家が書いたものか、それとも他方の作家のものか、
よりありうる方を決定したいと思います。
似た方法が、しばしば、スパムか合法的なメールかを識別するのに使われます。
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.
次のコードは、
文章を Doyle か Dowson に分類するのに、
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.03802079132 0.9619792087)
(bayes-query (parse "immense faculties and extraordinary powers of observation")
'DoyleDowson)
→ (0.985108793 0.01489120699)
最初の文章が Dowson文で、二番目のが Doyle文であると、
クエリは、正しく見分けます。
The queries correctly identify the first sentence as a Dowson sentence,
and the second one as a Doyle sentence.
二番目の例は、Bayesian 統計学の紹介文献にしばしば見られます。
前もって処理されたデータ・セットのデータ上で 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 を正しく動作させるために、
Bayesian 公式の使用は、イベント間の統計上独立を前提にしていることに、
注意して下さい。
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.
しばしば、データは、既に確率値として、利用できるようになっていて、
それらを頻度に戻す追加の仕事が要求されます。
最後の例では、データは、初めからパーセンテージで定義されています。
付加するオプション 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.
トークン(以下単語と記す)のジョイント・セットから、
単語 (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.
(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) (bayes-train '("one" "two" "two" "three") '("three" "one" "three") '("one" "two" "three") 'S) → (4 3 3) 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) (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 を記述するのに
bayesian ネットワークの紹介文や本で
よく使われる例から取っています。
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-train を MAIN でない他のコンテキストで使うには、
関数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 は、式のブロックをグループ化して使うことができます。
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 "================================"))
cond、
define、
doargs、
dolist、
dostring、
dotimes、
when、
while のような組込関数では、
その本体に、複数の式を持つことができますが、
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.
関数silent は、begin のように動作しますが、
戻り値のコンソール(端末)出力が抑えられます。
The silent function works like begin,
but suppresses console output on return.
ベータ 関数 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 は、
num-x 上の x の
ベータ 分布 betai の累積確率に等しくなります。
この累積2項分布は、確率 p が、
N 回試行中 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 回以上起こる確率を計算しています。 不完全ベータ分散は、数学や統計で、他の多くの関数を得るのに使われます。
(訳例: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))
;; という関係にあります
)
関数 binomial も見て下さい。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-eval が true なら、連想値は、評価されます:
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.
二項分布関数は、
イベントが float-p の確率を持ち、各試行で互いに独立である時、
int-n 中 int-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:
ここで、x! は、x の階乗、
pow(x, y) は、x の y 乗です。
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.
int の数値を 1 と 0 の文字列に変換します。
bool が nil 以外なら、リストを返します。
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 は、true と nil になり、
下位から上位への順になります。
これは、結果による直接索引やプログラム制御切替を可能にします。
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 の int は、bits の逆関数です。
int with a base of 2 is the inverse function to bits.
第一単純 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 ファイルの一部です。
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.
第二拡張 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
floationg point numbers passed in an out of the callback function.
単純及び拡張構文は同じプログラム内に混在できます。
Both the simple and extended syntax can be mixed inside the same program.
次に例には C ライブラリ関数 qsort の import があり、その引数の一つに比較関数のアドレスを取ります。
この場合には比較関数は 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-char、
get-int、
get-long、
get-string が使えます。
バイナリ・バッファや構造体からデータを取り出すには、
pack と unpack を使って下さい。
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.
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 は、exp の評価結果か
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 を返します。
評価中にエラーが発生すれば、
catch は、nil を返し、
エラー・メッセージを 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 が実行されると、
catch は true を返し、
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.
浮動小数点数 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.
カレント・ディレクトリを 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.
引数が文字列なら、引数の文字列 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".
Indexing elements of strings and lists を見て下さい。
See Indexing elements of strings and lists.
引数が整数なら、 char は、int 値の
アスキー・キャラクタの入った文字列を返します。
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 は、最後から int-char 個の文字を削除した
str のコピーを返します。
引数int-char が無い時は、一文字削除されます。
chop は、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)
述語 exp-predicate が、
list の各々の要素に適用されます。
返されるリストでは、述語が true となる全ての要素が、
除去されています。
(訳注:CommonLisp の remove-if と同じ。ただし、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 オプションで)
difference か
intersect を
使って下さい。
(訳注:difference と
intersect の
list オプションは、第三引数に 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.
int-file のファイル・ハンドルで指定されたファイルを閉じます。
ハンドルは、先行する open 操作から得られます。
成功すれば、close は、true を返し、
そうでなければ、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 を使うことは、
自動的に、0(ゼロ、スクリーン・デバイス)にリセットすることに注意して下さい。
Note that using close on device
automatically resets it to 0 (zero, the screen device).
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 は、ユーザ定義関数のシンボルか
lambda関数のどちらかを取ります。
イベント・ハンドラ関数が文字列を返さなければ、
コマンド・ラインは未翻訳のまま 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.
強制的にプロンプトになると、関数は空の文字列"" を返します。
To only force a prompt, the function should return the empty string "".
次の例では、コマンドが文字で始まる時、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/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
例では、過去において、
サーバー上の制御を獲得するのに Win32 ベースの悪意のある構成のウェブ・サーバーで、
スパマーが煩雑に使っていた技術を示しています。
The example shows a technique frequently used in the past by spammers on Win32 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 は、if のように、本体内の式を条件的に評価します。
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.
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) → ()
式 (cons 's nil) の結果として
(s) を返す他の Lisp と違って、
newLISP の cons は、(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 は、first と rest
の逆操作のように動作します(または、リストがペアなら、
first と last):
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)
関数的には、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.
set、
define、
define-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>
squareroot は、sqrt のように動作します。
+ (plus sign) は、
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 は、
異なる名前空間のコンテキストに切り替えます。
これに続く newLISPソースの load や
eval-string と sym のような関数は、
新たに生成するシンボルを新コンテキストに置きます。
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
コンテキストは、コピー可能です:
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.
現コンテキスト内でのシンボルは、
組込関数や、nil や true のような特殊シンボルのように
それらの名前だけで参照されます。
現コンテキスト外でのシンボルは、コンテキストのシンボル名と : (colon)
を先頭に付加することで、参照されます。
異なるコンテキスト内のシンボルの引用には、
コンテキスト名に ' (single quote) を付加します。
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 名前空間でのシンボルを生成できます。
これは、ハッシュや辞書の生成で使用すべきことに注意して下さい。
手始めに、ハッシュのような辞書として名前空間を使うより簡単な方法について、
Hash functions and dictionaries の章を見て下さい。
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? は、
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.
exp の評価式からコピーを作ります。
組込関数のいくつかは、破壊的 で、
動作中にオリジナルのリストやアレイ、文字列の中身を変更します。
copy と一緒に使えば、その動作を非破壊にできます。
Make 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"
関数replace や rotate に
copy を使うことで、オリジナル・データの変更は防がれます。
変更されたデータが返ります。
Using copy the functions replace and
rotate are prevented from changing the data.
A modified version of the data is returned.
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")
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
二変数 list-vector-X と list-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:
| name | description |
|---|---|
| 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)
study-time と test-errors の -0.926 という負の相関係数は、
帰無仮説下で尾部両側の p が約 0.0001 なので、高い有意性があります。
The negative correlation of -0.926 between study time and test errors is
highly signficant with a two-tailed p of about 0.0001 under the null hypothesis.
b0 = 29.241 と b1 = -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.
num-radians の双曲線余弦を計算します。
双曲線余弦は、次の数式で定義されます:
(exp (x) + exp (-x)) / 2
num-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
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 (zero)を示します。
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).
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.
(cpymem (pack "c c" 0 32) (last (dump 'sym)) 2)
(set 's "0123456789")
(cpymem "xxx" (+ (address s) 5) 3)
s → "01234xxx89")
最初の例は、シンボルsym の
プロテクション・ビットを削除します。
二番目の例は、
文字列変数に文字列を直接コピーします。
The first example would remove
the protection bit in symbol sym.
The second example copies a string directly
into a string variable.
次の例は、ゼロから新関数を作成し、
バイナリ・コードの部品を走らせ、二つの数を足し算します。
このアセンブリ言語小品は、
二つの数を足し算し、結果を返す X86 (Intel CPU) コードを示しています:
The 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 'foo-code (append
(pack "bbbbbbbbbb" 0x55 0x8B 0xEC 0x8B 0x45 0x08 0x03 0x45 0x0C 0x5D)
(if (= ostype "Win32") (pack "bbb" 0xC2 0x08 0x00) (pack "b" 0xC3))))
(set 'foo print)
(cpymem (pack "ld" (if (= ostype "Win32") 2312 1288)) (first (dump foo)) 4)
(cpymem (pack "ld" (address foo-code)) (+ (first (dump foo)) 12) 4)
(set 'foo-name "foo")
(cpymem (pack "ld" foo-name) (+ (first (dump foo)) 8) 4)
(foo 3 4) → 7
最後の例は、全てのハードウェア・プラットフォームや 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.
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.
統計的帰無仮説の有意を検定するために、
帰無仮説下で与えられた危険率(訳注:あるいは有意水準ともいう)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.
F検定を用いて統計的帰無仮説の有意を検定するために、
帰無仮説下で与えられた危険率(訳注:あるいは有意水準ともいう)num-probability と 自由度 int-df1 、int-df2 により、
最小限界 F 値を計算します。(訳注:EXCEL の FINV(確率, 自由度1, 自由度2)に相当。F分布)
Calculates the critical minimum F for a given confidence probability
num-probability under the null hypothesis and the degrees of freedmom
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.
統計的帰無仮説の有意を検定するために、 帰無仮説下で与えられた危険率(訳注:あるいは有意水準ともいう)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.
統計的有意と信頼区間を検定するために、
与えられた累積確率 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.
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/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.
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.
第一構文は、ローカル・タイム・ゾーンの現在の日付と時刻を
文字列表現で返します。
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.
第二構文では、date は、int-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 Win32 using # (date (date-value) 0 "%a %#d %b %Y") → "Mon 7 Mar 2005" (set-locale "de_DE") ; on Mac OS X (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
次の表は、 Win32 と Linux/Unix の両プラットフォームで利用可能な
全てのフォーマット指定子の要約です。
Linux/Unix では、さらに多くのフォーマット・オプションが利用可能です。
詳細は、個々のプラットフォームの Cライブラリにある
C関数 strftime() のマニュアル・ページを調べて下さい。
The following table summarizes all format specifiers available
on both Win32 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.
| format | description |
|---|---|
| %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 | day of the month as a decimal number (range 01–31) その月の日にち(レンジ 01–31) |
| %H | hour as a decimal number using a 24-hour clock (range
00–23) 24時間制で使われる時間(レンジ 00-23) |
| %I | hour as a decimal number using a 12-hour clock (range
01–12) 12時間制で使われる時間(レンジ 00-11) |
| %j | day of the year as a decimal number (range 001–366) 年間通しての日数(レンジ 001-366) |
| %m | month as a decimal number (range 01–12) 月数(レンジ 01-12) |
| %M | minute as a decimal number 分数 |
| %p | either 'am' or 'pm' according to the given time value
or
the corresponding strings for the current locale 与えられた時間よって 'am' か 'pm' のどちらか、あるいは、現ロケールに対応する文字列 |
| %S | second as a decimal number 0–61 (60 and 61 to account
for occasional leap seconds) 0-61 の秒数(60 と 閏秒を考慮した 61 ) |
| %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 | day of the week as a decimal, Sunday being 0 日曜を 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 | year as a decimal number without a century (range
00–99) 世紀を含まない年数(レンジ 00-99) |
| %Y | year as a decimal number including the century 世紀を含む年数 |
| %z | time zone or name or abbreviation (same as %Z on
Win32,
different on Unix) タイム・ゾーンの名前か省略形(Win32 では %Z と同じ、Unix では異なる) |
| %Z | time zone or name or abbreviation (same as %z on
Win32,
different on Unix) タイム・ゾーンの名前か省略形(Win32 では %z と同じ、Unix では異なる) |
| %% | a literal '%' character 文字 '%' |
日付の表示の先頭のゼロは、Linux や FreeBSD では "%-d" を使って、
OpenBSD や SunOS/Solaris や Mac OS X では、 "%e" を使って、省けます。Win32では、 "%#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 Mac OS X. On Win32 use "%#d".
date-value、
date-list、
date-parse、
time-of-day、
time、
now も見て下さい。
See also date-value, date-list,
date-parse,
time-of-day,
time, and now.
与えられた 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.
週の始めからの日数は、月曜日から日曜日に対して 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 (apply date-value (date-list 1282479244)) → 1282479244 (date-list 0) → (1970 1 1 0 0 0 1 4) ; Thursday 1st, Jan 1900
リストから特定の数値を返すのに、第2オプション・パラメータが使えます。
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.
テキスト文字列 str-date から、
dateで見られる同じフォーマット・ルールを使った
str-format で定義されたフォーマットで、
日付を解析します。
関数 date-parse は、UTC 1970年1月1日 を 0 として経過した UTC 秒数を
2038年1月19日の 2147472000 まで返します。
1970年1月1日より前では、負の値が 1901年12月14日の -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. For dates before January 1st 1970, negative values
are returned down to a value of -2147472000 for December 14th, 1901.
この関数は、Win32プラットフォームでは、利用できません。
以前のバージョンでは、parse-date と呼ばれていました。
This function is not available on Win32 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 は、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.
第二構文では、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 1970 1 1 0 0 0) → 0 (date (apply 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-list は、date-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) (apply date-value (date-list 1014854400)) → 1014854400
date、
date-list、
date-parse、
time-of-day、
time、
now も見て下さい。
See also date,
date-list, date-parse,
time-of-day, time, and
now.
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 モード中に、エラー・メッセージが出力されることがあります。例外を起こした関数が 0 か nil を返して、プロセスを続けます。このように、デバック中は、変数とプログラムの現在の状態は監視されたままになります。
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.
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.
この関数は、new のように動作しますが、
sym-source のシンボルから
一つのシンボルとそのコンテキストのコピーのみを作ります。
sym-target が無い時は、
同じ名前のシンボルが、現コンテキストに作られます。
sym-source 内で参照可能な全てのシンボルが、
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.
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.
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))
lambda または fn 式は、シンボルに定義すること無しに、 それ自身で匿名関数として使われることもあります: 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
fn は、lambda 記述の短縮形です。
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 で定義された関数は、
他のLISPのように、変数を展開しない fexpr と呼ばれます
(訳注: fexpr とは、
オペランドが評価されずに渡される関数)。
newLISP では、今まで通り、マクロと呼ばれています、
というのも、それらが、引数の標準的でない評価パターンとして
特殊な構文形式を作るという同じ目的で書かれるからです。
define-macro を使って作られた関数は、
expand や letex を使った
テンプレート展開式と結合可能です。
Functions defined using define-macro are called fexprs
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.
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)
fexprs では、
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
例題の定義では、レキシカルに隔離されていて、
変数捕捉が起こりません。
(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))))
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.
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.
組込関数のようなプロテクトされたシンボルとか nil や true のような特殊シンボルは、削除できません。
Protected symbols of built-in functions and special symbols
like nil and true cannot be deleted.
delete は、シンボルの削除に成功すると true を返し、
失敗すると nil を返します。
delete returns true if the symbol was deleted
successfully or nil if the symbol was not deleted.
(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.
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.
この関数は、
リモート 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-url が file:// で始まっていれば、
ローカル・ファイル・システム上のファイルが削除されます。
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.
int-pid のプロセスIDでプロセスを破棄し、
成功すると true、失敗すると nil を返します。
プロセスIDは、先行する Mac OS X や 他の 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 Mac OS X and other Unix or
process on all platforms. On Unix, destroy works like
the system utility kill using the SIGKILL signal.
注意! int-pid が 0 ならば、
送り側のプロセス・グループ 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 を指定した時、destroy は、
int-pid のプロセスに指定された Unix シグナルを送る
Unix kill コマンドのように動作します。
この第二構文は、Win32 では利用できません。
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 Win32.
(set 'pid (process "/usr/bin/bc" bcin bcout)) (destroy pid) (set 'pid (fork (dotimes (i 1000) (println i) (sleep 10)))) (sleep 100) (destroy pid)
正方行列の行列値を返します。
行列は、入れ子リストと アレイ のどちらも可能です。
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.
他の行列操作
invert、
mat、
multiply、
transpose
も見て下さい。
See also the other matrix operations
invert, mat,
multiply and transpose.
int-handle は、
stdin として 0 、stdout として 1 にセットされている
デフォルトの標準 I/O のハンドル・ペアとして 0 (zero) にセットされている
I/Oデバイス番号です。
int-handle は、
open を使って先行して得られるファイル・ハンドルでもあります。
両者の場合とも、入力と出力が、このハンドルを通して、割り当てられます。
引数がないと、現在のI/Oデバイス番号が返ります。
int-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 and 1
for stdout. int-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 チャンネルは、
関数 print や read-line の
内部で使われます。
現在の I/O デバイスが、0 か 1 の時は、print は出力をコンソール・ウィンドウに送り、
read-line はキーボードから入力を受け取ります。
現在の I/O デバイスが、開いているファイルにセットされているなら、
print や read-line は、
そのファイルに対して動作します。
The I/O channel specified by device is used internally
by the functions print and 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.
(device (open "myfile" "write")) → 5 (print "This goes in myfile") → "This goes in myfile" (close (device)) → true
device に、close を使うと、
自動的に、device は、0 (zero) にリセットされることに注意して下さい。
Note that using close on device
automatically resets device to 0 (zero).
第一構文では、difference は、
list-A と list-B 間の集合 差を返します。
結果のリストは、list-A に有って、
list-B に無い要素のみ持ちます。
結果のリストの全要素は、単一(訳注:重複する要素が無い)ですが、
list-A と list-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 は、list モードで動作します。
bool は、true か nil以外に評価される式です。
結果のリストでは、list-B の全要素が、list-A から除かれますが、
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)
集合関数 intersect や
unique、union も見て下さい。
See also the set functions intersect,
unique and union.
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のルート・ディレクトリのディレクトリ・エントリの
リストを返します。
Win32 システムで、
フォーワード・スラッシュ (/) がパス名に使えることに、注意して下さい。
バックスラッシュ (\) を使う時は、
二つの目のバックスラッシュの前置きが必要です。
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 Win32 systems,
a forward slash (/) can be included in path names.
When used, a backslash (\) must be
preceded by a second backslash.
第二構文で、directory は、
str-pattern の正規表現パターンをとることができます。
ディレクトリ・エントリのリスト中で
パターンに一致するファイル名だけが返ります。
int-options で、特殊正規表現オプションを指定できます。
詳細は、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 int-regex-options, 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".
正規表現を使う他の関数には、
find、find-all、
parse、
regex、replace、
search があります。
Other functions that use regular expressions
are find, find-all,
parse,
regex, replace,
and search.
str-path がディレクトリかどうかをチェックします。
結果により、true か nil が返ります。
Checks if str-path is a directory.
Returns true or nil depending on the outcome.
(directory? "/etc") → true (directory? "/usr/bin/emacs/") → nil
num-2 以下の数値で
num-1 を連続的に除算します。
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 のみの時、
div は、num-1 の逆数を計算します。
When num-1 is the only argument,
div calculates the inverse of num-1.
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.
関数while と
do-while も見て下さい
(訳注:until も)。
See also the functions while
and do-while.
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.
関数until
と do-until も見て下さい
(訳注:while も)。
See also the functions until
and do-until.
ユーザ定義関数やマクロで、引数リストの総数分繰り返します。
この関数やマクロは、define、
define-macro、lambda、
lambda-macro を使って定義できます。
sym の変数には、引数リストの要素が、リストが空になるか、
(exp-breakに定義される)オプションの脱出条件が true か
論理的真値に評価されるまで、次々にセットされます。
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.
list の各要素毎に、body の式群が、評価されます。
本体式群が評価される前に、変数 sym は、各要素にセットされます。
ループ・インデックスとして使われる変数は、
局所変数で、ダイナミック・スコープのルールに従って振舞います。
The expressions in body are evaluated
for each element in list.
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 を表示します。
dolist が、実行された後でも、
dolist の x が、ローカル・スコープなので、
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.
string の各キャラクタ毎に、body の式群が、評価されます。
本体式群が評価される前に、
変数 sym は、各 ASCII 値 か UTF-8 の整数値にセットされます。
ループ・インデックスとして使われる変数は、局所変数で、
ダイナミック・スコープのルールに従って振舞います。
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.
body の式群は、int 回評価されます。
本体式(群)が、評価される前に、毎回、
変数sym-var は、0 (zero) から (int - 1) までにセットされます。
ループ・インデックスとして使われる変数は、dotimes での局所変数で、
ダイナミック・スコープのルールに従って振舞います。
ループ・インデックスは、整数型です。
dotimes は、body 中、最後に評価された式の結果を返します。
dotimes 宣言文の評価が終わった後、sym-var は以前の値になります。(訳注:15.ダイナミック スコープとレキシカル スコープの章を参照して下さい。)
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.
sym-context の全てのシンボルで、body の式群は、評価されます。
シンボルは、ソート順にアクセスされます。
本体の式(群)が各々評価される前に、変数sym は、
sym-context からのシンボルに次々とセットされます。
ループ・インデックスとして使われる変数は、dotdotree での局所変数で、
ダイナミック・スコープのルールに従って振舞います。
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 keys や
bayes-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.
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:
| offset | description |
|---|---|
| 0 | newLIPセルのメモリ・アドレス memory address of the newLISP cell |
| 1 | cell->type: major/minor 型、詳細は、 newlisp.h を見て下さい。 major/minor type, see newlisp.h for details |
| 2 | cell->next: リスト・ポインタへのリンク linked list ptr |
| 3 | cell->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 |
| 4 | cell->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.
exp の式が、文字列に評価されたなら、
その文字列を int-n回、反復して返します。
bool に nil 以外に評価される式が指定されると、
文字列は、連結されずに、他のデータ型のように、リストで反復されます。
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.
関数 sequence や
series も見て下さい。
See also the functions sequence
and series.
exp が空のリスト
(あるいは、str が空の文字列)かどうかをテストします。
引数に要素を含んでいるかどうかで、
true か nil が返ります。
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.
str-pad の暗号化パッドを使って、
str-source のワン・タイム・パッド暗号化を実行します。
str-pad が長く、バイト列がランダムであればあるほど、
暗号化は、より安全です。
パッドがソース・テキストより長ければ、
完全にランダムで、一回だけ使われ、
ワン・タイム・パッド暗号化されたデータは、
一見ランダムなデータのように見え、
ほとんど解読不可能になります。
オリジナルの回収には、
同じ関数とパッドを暗号化テキストに適用します:
Performs a one-time–pad 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 は、str-data の文字列が
str-key で指定された文字列で終わるかどうかをテストします。
結果次第で、true か nil を返します。
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 は、
exp のリスト要素で (訳注:list の)リストが
終わっているかどうかをチェックします。
結果次第で、true か nil が返ります。
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.
第一構文(引数無し)では、オペレーティング・システム環境が、
各エントリーが環境変数と値の対となる連想リストとして取り出されます。
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/bin/") → true (env "NEWLISPBIN") → "/usr/bin/" (env "NEWLISPBIN" "") → true (env "NEWLISPBIN") → nil
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)
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.
(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 は、expの評価結果を現変数環境で評価します。
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 で
参照により引数を渡す安全な方法です。
Passing objects by reference の章を見て下さい。
名前空間を使ったユーザ定義関数に参照を渡すことは、
渡されたシンボルが関数のパラメータとして使われている名前と同じ場合に起こりうる
シンボル渡し時の変数補足 を避けます。
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.
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.
最後の例は、翻訳時に使いたいコンテキストを指定する方法を示しています。
これで、シンボル a と b は、
MAIN の代わりにコンテキスト 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.
整数値が 2 でちょうど割り切れ、余りが無いことをチェックします。
浮動小数点が int-number に渡された時は、小数部分が切り捨てられた整数として扱われます。
Checks if an integer number is even divisable 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 divisable by 2.
第一形式では、exec は、str-process に記載されているプロセスを起動し、
すべての標準出力を(標準出力(STDOUT)の各ライン毎に一つの)文字列のリストで返します。
プロセスを起動できなかった場合、exec は、nil を返します。
プロセスが起動しても、改行のみやエラーや出力なしの場合は、空リストが返ります。
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.
func-condition を list の要素に次々と適用して、
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-condition が nil? ならば、
結果の nil は、どちらにでも取れます。
この場合は、index か find が、
nil を見つけるより良い方法です。
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.
newLISP を終了します。
オプションの終了コード、int、が与えられます。
このコードは、ホストのオペレーティングシステムでテストされます。
newLISP がコマンド・ライン・オプション -d を使って
daemon server mode で走っている時は、
ネットワーク接続のみが閉じられ、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)
num の式が評価され、
その結果のもとに(訳注:底が e の)指数関数を計算します。
exp は、log の逆関数です。
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
第一構文では、
sym(あるいは、sym-2 から sym-nの複数シンボル) の1シンボルが、
単純な式もしくは入れ子の式 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 inside 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 は、引数リストを畳み込み(reduce) します。
Like the apply function,
expand reduces its argument list.
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:
bool が true に評価されると、
連想リストの値の部分が評価されます。
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)
連想リストの変数の内容は、変化しないことに注意して下さい。
これは、変数が評価して連想部分に割り当てることよってセットされる
関数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.
第三構文は、大文字で始まる変数の内容を展開する時にのみ使います。
この 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でない中身も持つ
シンボル A と Bvar のみが、
展開されます。
Only the symbols A and Bvar are expanded
because they have capitalized names
and non-nil contents.
expand の第一構文を実演している例の
カレー化(currying) 関数は、
大文字変数を使ってより簡単に書けます。
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 > _
展開機構を提供する関数 letex や
expand と一緒によく使われる関数 unify を見て下さい。
See the letex function,
which also provides an expansion mechanism,
and the function unify,
which is frequently used together with expand.
第一構文では、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))
関数 join や append は、
explode 操作の逆です。
The join and append functions
are inverse operations of explode.
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 (zero) 文字を含むことができます。
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.
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)
2 より小さい数値で、
factor は、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 (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 ;; 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.
str_nameのファイルかディレクトリの情報のリストを返します。
オプションのインデックスで、戻り値のリスト番号を指定できます。
bool-flag が指定されないか、nilに評価されると、
ファイルがオリジナル・ファイルにリンクしていても、リンクの情報が返ります。
bool-flag が nil 以外に評価されると、
リンクで参照されるオリジナル・ファイルの情報が返されます。
(訳注:リンクは、Windows のショート・カットとは違います。
つまり、Win32では、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.
| offset | contents |
|---|---|
| 0 | size |
| 1 | mode (differs with true flag) |
| 2 | device mode |
| 3 | user ID |
| 4 | group 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-info は、mode 部以外は、
リンクではなく、リンクされているファイルのファイル統計値 (size) を与えます。
file-info gives file statistics (size) for a linked file,
not the link, except for the mode field.
str-name のファイルの存在をチェックします。
ファイルが存在すれば true を、そうでなければ、 nil を返します。
この関数はデレクトリに対しても true を返します。
オプションの bool 値が true なら、str-path-name が返ります。
ファイルの存在は、読み書きの許可等の情報を含みません。
ファイルは、カレント・ユーザによる読み書きの許可を持たない存在かもしれません。
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,
str-path-name is returned. The existence of a file does not imply anything about
its read or write permissions. A file may exist while not having the permissions
to read from or write to it by the current user.
(if (file? "afile") (set 'fileNo (open "afile" "read"))) (file? "/usr/bin/newlisp" true) → "/usr/bin/newlisp" (file? "/usr/bin/foo" true) → nil
exp-predicate の述部を exp-list のリストの各要素に適用します。
exp-predicate が true となる要素からなるリストが返ります。
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 と
述部が false(訳注: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.
第二引数list がリストに評価されてなら、
find は、exp-key の評価から得られる要素の
インデックス位置 (offset) を返します。
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 が文字列なら、正規表現オプションが、
int-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 int-regex-option parameter.
正規表現か、比較関数オブジェクト(functor)を使った時は、
システム変数 $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)
match や unify を使ったリスト検索は、
文字列に対する正規表現のよりパワフルな定型化が可能になります。
Using match and unify,
list searches can be formulated which are as powerful
as regular expression searches are for strings.
第二引数 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 (one) か、区別する 0 (zero) かの)
int-option で指定されるオプション番号と共に
str-pattern の正規表現パターンを使った検索を指定します。
int-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 int-regex-option
(i.e., 1 (one) for case-insensitive search or 0 (zero)
for no special options). If int-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 を指定するには、
int-regex-option に nil を指定して下さい。
To specify int-offset in a simple string search without regular
expressions, specify nil for int-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"
他に正規表現を使う関数として、
directory、
find-all、
parse、
regex、
replace、
search を見て下さい。
For other functions using regular expressions,
see directory,
find-all,
parse,
regex,
replace,
and search.
入れ子になった式や多次元リストの検索には、
ref や ref-all を使って下さい。
To find expressions in nested
or multidimensional lists,
use the ref and ref-all functions.
第一構文では、find-all は、テキストstr-text 中に
str-regex-pattern の出現を全て見つけ、一致した全ての文字列のリストを返します。
一致するものがなかった時、空リスト() が返ります。
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.
オプションで、見つかった文字列や正規部分表現を戻りリストに入れる前に処理する式を指定できます。
追加オプション int-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, int-option,
specifies special regular expression options
(see regex for further details).
(find-all {\d+} "lkjhkljh34ghfdhgfd678gfdhfgd9")
→ ("34" "678" "9")
(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")
最初の例は、テキスト中の全ての数字を見つけています。
二番目の例は、正規表現パターン 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 は、int-option がなくても、
常に、正規表現検索を実行することに注意して下さい。
Note that find-all with strings always performs a regular expression search,
even if the option in int-option is omitted.
第二構文では、find-all は、list-lists 中で
パターン list-match-pattern に match する全てのリストを検索します。
文字列に対しての find-all のように、
match した部分リストを操作する exp を指定できます:
In the second syntax, find-all searches for all list match patterns list-match-pattern in list-lists. As in find-all for strings, an expression can be specified in exp to process further the matched sublist:
(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)
リスト match のための 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")
検索する式やリストに含める式は、どんな型も可能です。
この構文の find-all は、filter のように動作しますが、
見つけた要素を処理する式を定義できるという追加の利点があります。
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.
リストの最初の要素や文字列の最初の文字を返します。
引数は変わりません。この関数は、他の Lisp方言の car
や head と等価です。
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 は、
バイト境界ではなく、キャラクタ境界で動作します。
関数 last
や rest も見て下さい。
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.
フラットなリストを返します
(訳注:入れ子の括弧をなくし、アトムのみのリストにする):
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))
flat なら、入れ子リストでも繰り返しに使えます。
flat can be used to iterate through nested lists.
exp の式が、数値か文字列に評価されたなら、
引数は、浮動小数点数に変換され、返されます。
exp が、浮動小数点数に変換できないなら、
nil か、指定された exp-default の評価が返されます。
この関数は、主に、ユーザ入力や、テキストの読み取り・解析時の
文字列の変換に使われます。
文字列は、数値か + (plus sign) か - (minus sign) か
. (period) で始まっている必要があります。
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.
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)) trueNaN や INF の型は、浮動小数点数です。)
浮動小数点数の 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.
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 は、
map や sort 等の
関数が引数として使われる他の多くの関数でよく使われる
無名関数の定義に使われます。
fn is used to define anonymous functions,
which are frequently used in map,
sort,
and many other functions where functions can be used as arguments.
無名関数を使えば、
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 を使って、
引数のリストに展開されます(mapped) 。
二番目の例は、長さでソートされる文字列を示しています。
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)
can be used in place of fn.
num-from と num-to により
指定される範囲(num-from と num-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 の評価前にテストされます。
中断条件は、 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.
シンボル sym は、for 式内の
ダイナミック・スコープでローカル変数です。
刻み幅が指定されない時は整数で、
刻み幅がある時は浮動小数点数で、
指定された範囲内の各値を連続して取ります。
(訳注:刻み幅がない時は、sym は整数ですが、刻み幅を指定すると、
num-from と num-to が整数値であっても、
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.
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.
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.
プロセスの起動や結果の収集をより簡単に自動化する方法として、
spawn や Cilk 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/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.
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 は、
有効なフォーマット文字列の有効性、データ型の一致、引数の数が合っているかを
チェックします。
間違ったフォーマットやデータ型には、エラー・メッセージが返ります。
int や float や
string が、、
適正なデータ型の保証や、エラー。メッセージの回避に使えます。
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:
% (percent sign) が、フォーマット指定を開始します。 フォーマット文字列内で % を表したい時は、 2度書きします:%%
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 | character (value 1 - 255) |
| d | decimal (32-bit) |
| u | unsigned decimal (32-bit) |
| x | hexadecimal lowercase |
| X | hexadecimal uppercase |
| o | octal (32-bits) (not supported on all compilers) |
| f | floating point |
| e | scientific floating point |
| E | scientific floating point |
| g | general floating point |
32ビット・フォーマット子を使って64ビット数値を定型化すると、
切り詰められ、下位の32ビット数字が整形されます。
Formatting 64-bit numbers using 32-bit format specifiers will truncate and
format the lower 32 bits of the number.
Unix-ライクOSでは、64ビット数値に、下記のフォーマット文字列を使って下さい:
For 64-bit numbers use the following format strings on Unix-like
operating systems:
| format | description |
|---|---|
| lld | decimal (64-bit) |
| llu | unsigned decimal (64-bit) |
| llx | hexadecimal (64-bit) |
| llX | hexadecimal uppercase(64-bit) |
(version 8.9.7以降)Tru64 Unix では、 64ビット数値に、下記のフォーマット文字列を使って下さい:
For 64-bit numbers (since version 8.9.7) use the following format
strings on Tru64 Unix:
| format | description |
|---|---|
| ld | decimal (64-bit) |
| lu | unsigned decimal (64-bit) |
| lx | hexadecimal (64-bit) |
| lX | hexadecimal uppercase(64-bit) |
Win32プラットフォームでは、64ビット数値に、下記の文字列を使って下さい:
On Win32 platforms the following characters apply for 64 bit numbers:
| format | description |
|---|---|
| I64d | decimal (64-bit) |
| I64u | unsigned decimal (64-bit) |
| I64x | hexadecimal (64-bit) |
| I64X | hexadecimal uppercase(64-bit) |
他のテキストはフォーマット指定子間かフォーマット指定子の前後に置けます。
Other text may occur between,
before, or after the format specs.
Tru64 Unix では、フォーマット文字 i が、
d の代わりに使えることに注意して下さい。
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 "%-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
支払い定額 num-pmt と固定利率 num-rate で
最初の元金 num-pv と支払回数 num-nper 後の
未来のローン残高を計算します。
支払いが、期間の終わりなら、int-type は、0 (zero) か省略し、
支払いが、期間の始めなら、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.
関数 irr、
nper、
npv、
pmt、
pv も見て下さい。
See also the functions irr,
nper, npv,
pmt, and pv.
num-a と num-b で各々指定される
値 a と b の不完全ガンマ関数を計算します。
(訳注:第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.
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 は、 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.
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.
関数address、
get-int、
get-long、
get-float、
get-string、
pack、unpack も見て下さい。
See also the address,
get-int,
get-long,
get-float,
get-string,
pack, and unpack functions.
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.
関数address、
get-int、
get-long、
get-char、
get-string、
pack、
unpack も見て下さい。
See also the address,
get-int,
get-long,
get-char,
get-string,
pack,
and unpack functions.
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.
関数address、
get-char、
get-float、
get-long、
get-string、
pack、
unpack も見て下さい。
See also the address,
get-char,
get-float,
get-long,
get-string,
pack,
and unpack functions.
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.
関数address、
get-char、
get-float、
get-int、
get-string、
pack、
unpack も見て下さい。
See also the address,
get-char,
get-float,
get-int,
get-string,
pack,
and unpack functions.
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-char、
get-int、
get-float、
pack、
unpack も見て下さい。
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.
str-url の URL で指定されたウェブ・ページかファイルを
HTTP プロトコルを使って読み込みます。
http:// と file:// のどちらの URL も処理されます。
"header" は、ヘッダーだけを取り出すために
str-option の引数オプションに指定可能です。
"list" オプションは、ヘッダーとページ情報を分離して、
文字列のリストにして返します。
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.
"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-url は、
ERR: で始まる文字列とエラーの説明を返します。
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-url は、 Transfer-Encoding: chunked フォーマットも理解し、
データを chunked フォーマット解除に解凍(unpack)します。
(訳注: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.
get-url の要求は、newLISP サーバーでも受け付けられます。
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:
カスタム・ヘッダーには、
ブラウザ・クッキーや他のサーバーへの指示のための
オプションが入ります。
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 v8800 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-url や post-url でも使えます。
Custom headers can also be used
in the put-url
and post-url functions.
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 化し、保護するのに、
一つの宣言文で、constant と global を
使う方法を示しています。
The second example shows how constant
and global can be combined into one statement,
protecting and making a previous function definition global.
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
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.
(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
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" は、オプションです。
このオプションが無い時は、
条件-式ペアの括弧を要求することなしに
伝統的な cond のように厳密に振る舞い、
式(>= x 30) の評価が返ります。
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.
関数 unless も見て下さい。
See also the unless function.
FFT 法(高速フーリエ変換)を使って、
複素数リスト list-num の離散的逆フーリエ変換を計算します。
各複素数は、その実数部とそれに続く虚数部で指定されます。
実数部のみ使う場合は、虚数部に、0.0 (zero) をセットします。
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.
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 libary 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 loading libraries
without importing functions. This is necessary when other libraries need access
to functions they need internally.
ほとんどのライブラリ関数が単純な第一構文を使って導入できます。
API は関数の引数全てを cdecl や stdcall 規則の
スタックで渡されるものと期待しています。
32 ビットのプラットフォームでは、整数、文字列のポインタ、
浮動小数点数値のバッファをパラメータとして渡すことができます。
64 ビットのプラットフォームでは、整数のみを渡すことができ、
浮動小数点数値は渡すことができません。
戻り値としては、32 ビット値 か 64 ビット値とポインタのみが許されます。
浮動小数点数を戻すことはできません。
文字列は、get-string 補助関数を使って取り出す必要があります。
このような制限がありますが、配布中に含まれるほとんどのモジュールは、
この単純 import API を使っています。
Most library functions can be imported using the simpler first syntax. 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-char、
get-int、
get-float、
get-string、
pack、
unpack
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
構造体データのポインタを渡すためには、次の関数がデータのパックやアドレス計算の助けとなります:
address、
pack。
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 '(
("Win32" "msvcrt.dll")
("OSX" "libc.dylib")
(printf "%g %s %d %c\n" 1.23 "hello" 999 65)
1.23 hello 999 A
→ 17 ; return value
;; import Win32 DLLs in Win32 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)
他の例は、Win32 DLL 関数のいくつかの導入と、
即値 や参照 による引数の与え方を示します。
文字列や数を参照で渡す時は、事前に場所を用意しておく必要があります。
The other examples show several imports of Win32 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"
Win32 や Cygwin 版の newLISP は、DLLライブラリ・ルーチンの呼び出しに、
デフォルトで標準呼び出し stdcall 手続きを使います。
これは、Win32 オペレーティング・システムに属する
DLL (例えば、odbc32.dll) の呼び出しには、必要なことです。
多くのサード・パーティの DLL は、C 宣言 cdecl 呼び出し手続きでコンパイルされ、
関数を導入する時に、追加のする最後の引数に文字列 "cdecl" の指定を必要とするかもしれません。
Mac OS X や Linux や 他の Unix システムでコンパイルされたnewLISP は、
デフォルトで、 cdecl 呼び出し手続きでを使いますので追加の文字列は無視します。
The Win32 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 Win32 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 Mac OS X, Linux and other Unix systems uses the
cdecl calling conventions by default and ignores any additional string.
;; force cdecl calling conventions on Win32
(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).
拡張 import API は第二構文で動作します。
それは、よく知られている libffi ライブラリに基づいており、
ほとんどの OS プラットフォームに予めインストールされています。
この API は、パラメータ渡しや戻り値に C言語のデータ型を使って動作します。
API は、パラメータの型が import 構文で指定されている必要があります。
型指定には、型の文字列ラベルを使います。
拡張 import API で書かれたプログラムは、
32 ビットと 64 ビットの newLISP とライブラリで
変更することなく、走るでしょう。
補助関数を使うことなしに、整数、浮動小数点数、文字列を戻せます。
The extended import API works with the second syntax. It is based on the popular
libffi library and is pre-installed on most OS platforms. 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:
| label | C type for return value and arguments | newLISP return and argument type |
|---|---|---|
| "void" | void (only as return type) | nil is returned |
| "byte" | byte unsigned 8 bit | integer |
| "char" | char signed 8 bit | integer |
| "unsigned short int" | unsigned short int 16 bit | integer |
| "short int" | short int signed 16 bit | integer |
| "unsigned int" | unsigned int 32 bit | integer |
| "int" | int signed 32 bit | integer |
| "long" | long signed 32 or 64 bit depending on platform | integer |
| "long long" | long long signed 64 bit | integer |
| "float" | float 32 bit | IEEE-754 64 bit float cut to 32-bit precision |
| "double" | double 64 bit | IEEE-754 64 bit float |
| "char*" | char* 32 or 64 bit ptr depending on platform | displayable string return (zero terminated) string buffer arg (no addr. since 10.4.2) |
| "void*" | void* 32 or 64 bit ptr depending on platform | integer 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.
次の例は、拡張 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*" を使うと、結果のバッファ・アドレスが戻ります。
これは、構造体データへのポインタを返す時に役立ちます。
このポインタから構造体の中身を取り出すには、unpack and struct を使います。
次の例では、戻り値の型を 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 bufffer 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.
導入した外部関数により実行された割り当ては、
導入した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.
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
place シンボルが nil を含むなら、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.
述部 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)) → (1 3 6)
述部は、組込述語か、ユーザ定義関数か、ラムダ式です。
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.
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.
exp の式が、数値か文字列なら、結果は、整数に変換され、返されます。
exp が整数に変換できない時は、nil か、exp-default の評価結果が返ります。
この関数は、ユーザ入力やテキスト解析による文字列の変換によく使われます。
exp が文字列に評価される場合、文字列は、数字か、一個以上のスペースか、
+ か - サインで 始まっていなければなりません。
16進数文字列は、'0x' で、8進数文字列は、'0' (zero) で始まっている必要があります。
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 (zero) に変換されます。
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 "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.
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 は、
list-A と list-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)
第二構文では、(訳注:intersect は、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)
集合関数 difference や
unique、unionも見て下さい。
See also the set functions
difference, unique
and union.
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-pivot に 0.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 (zero) になります。
行列は、入れ子のリストでも 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 が指定されていなければ、invert は nil を返します。
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.
行列関数 det、
mat、
multiply、
transpose も見て下さい。
See also the matrix functions det,
mat, multiply
and transpose.
期間あたりのキャッシュ・フローの内部収益率を計算します。
内部収益率は、キャシュ・フローの現在の価値を 0.0 (zero) にする金利です。
流入(負数)と流出(正数)の総額を list-amounts に指定します。
list-times に期間倍率が指定されていない場合、
list-amounts は、1ずつ(1, 2, 3–という風に)増加する期間倍率で合計されます。
使っているアルゴリズムは、初期推定値0.5 (50%) の反復法です。
オプションで、異なる初期推定値を指定できます。
アルゴリズムは、精度が 0.000001 (0.0001%) に達した時、戻ります。
nil は、アルゴリズムが、50回で収束しなかった時に返ります。
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 (zero) になるならば、
それは、約年利 20.2 %の配当に相当します。
次の行は、 irr と npv の関係を示しています。
(訳注:三行目は、)三年後から、回収が始まるのであれば、最低限 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.
関数 fv、
nper、
npv、
pmt、
pv も見て下さい。
See also the fv,
nper,
npv,
pmt,
and pv functions.
与えられた list-of-strings の文字列のリストを
(訳注:間にスペースを入れて)つなぎ合わせます。
str-joint があれば、(訳注:スペースの代わりに)
結合時、それが(接続文字として)各文字列間に挿入されます。
bool-trail-joint が true なら、
接続文字が文字列の最後にも追加されます。
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-"
関数 append や string と
join 操作と逆の explode も見て下さい。
See also the append,
string,
and explode functions,
which are the inverse of the join operation.
lambda の省略形である fn の説明を見て下さい。
See the description of fn, which is a shorter form of writing lambda.
define-macro の説明を見て下さい。
See the description of define-macro.
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 式についてのさらなる情報は、
define や define-macro を
見て下さい。
See define and define-macro for
more information about lambda expressions.
リストや文字列の最後の要素を返します。
(訳注: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 は、バイト境界ではなく、キャラクタ境界で動作します。
first、rest、
nth も見て下さい。
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.
シンタックス・エラーやリソースの枯渇に起因する newLISP で生じた最後のエラーを報告します。
起こりうる全てのエラーのまとめは、付録の Error codes の章を見て下さい。
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 userdefined 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.
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.
リストの要素数、アレイの行数、文字列のバイト数を返します。
Returns the number of elements in a list, the number of rows in
an array, or the number of bytes in a string.
シンボルに適用した length は、シンボル名の長さを返します。
数値に適用すると、length は、整数なら 4 か 8 、浮動小数点数なら 8 という風に
数値を格納するのに必要なメモリのバイト数を返します。
length applied to a symbol returns the length of the symbol name.
Applied to a number, length returns the number of bytes needed in
memory to store that number: 4 or 8 for integers and 8 for floating point numbers.
(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 (set 'ary (array 2 4 '(0))) → ((1 2 3 4) (5 6 7 8)) (length ary) → 2 (length "Hello World") → 11 (length "") → 0 (length 'someVar) → 7 (length 123) → 8 (length 1.23) → 8 (length (get-int "\000\000\000\001")) → 4
UTF-8文字数の計算には utf8len を使って下さい。
Use utf8len to calculate the number of UTF-8 characters
in a string.
一個以上の変数 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)))
(訳例:> (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 にしようとして、 Common Lisp のように記述すると、不用意に (上記、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 が便利です。)
変数 x と y が初期化されてから、式 (+ 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 用の letn と
nil に初期化する local も見て下さい。
See also letn for an incremental or nested form of
let and local for initializing to nil.
この関数は、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) が、評価を得る前に、x、y、zは、
letex の初期化リストからの初期値で、文字通り置き換えられます。
最終的に評価を得る式は、 '(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 は n を定数 3 に評価して、ラムダ式内の c と置き換えます。
(訳注:let や letn で定義した変数では、ラムダ式内の変数を置き換えることはできません。)
letex evaluates n to the constant 3 and replaces c
with it in the lambda expression.
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.
次の let と letn の比較が、その違いを示しています:
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 を使っている最初の例では、
変数 y は、let 式より前に束縛された 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.
exp が評価され、その値は、新しいリストを構成するのに使われます。
アレイ型の引数は、リストに変換されますので注意して下さい。
The exp are evaluated and the values used to construct a new list.
Note that arguments of array type are converted to lists.
(list 1 2 3 4 5) → (1 2 3 4 5) (list 'a '(b c) (+ 3 4) '() '*) → (a (b c) 7 () *)
リストに束縛する他の形式として cons や push も見て下さい。
See also cons and push for other
forms of building lists.
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
一個以上の 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/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.
第一構文では、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).
連想リスト 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.
Indexing elements of strings and lists も見て下さい。
See also Indexing elements of strings and lists.
lookup は、assoc に似ていますが、
見つかったリストから指定した要素を取り出す手間が省けます。
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"
文字列 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-case や title-case も見て下さい。
See also the upper-case and
title-case functions.
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
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/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/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/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/bin/newlisp" "./script" "1" "2" "3")
このスクリプトを異なるコマンド・ライン・パラメータで試してみて下さい。
Try executing this script with different
command-line parameters.
str-dir-name で指定されたディレクトリを
オプションのアクセス・モード int-mode で作ります。
結果によって true か nil を返します。
アクセス・モードの指定がなければ、
多くの 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 (octal) です。
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 (octal 750 = drwxr-x---)の
アクセス・モードで、カレント・ディレクトリに作ります。
This example creates a directory named adir
in the current directory with an access mode of
0750 (octal 750 = drwxr-x---).
組込関数、定義関数、ラムダ式の exp-functor を
list-args-1, list-args-2– で指定される引数に、
連続的に適用して、全ての結果をリストで返します。
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.
(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)) >)
構文に括弧を使うような特殊な形式(例えば caseとか)は、マップできません。
Special forms which use parentheses as syntax cannot be mapped
(i.e. case).
第一構文では、
この関数は、matrix-A と matrix-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 で直接コード化したものと同じくらい高速にします。
同じことが、行列演算 multiply や invert にも、言えます。
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))
他の行列演算 det、
invert、
multiply、
transpose も見て下さい。
See also the other matrix operations det,
invert, multiply,
and transpose.
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 は、合致した式のリストを返します。
各? (question mark) に対しては、合致している式要素が返ります。
各+ (plus sign) または、* (asterisk) に対しては、
合致した要素からなるリストが返ります。
パターンが、list-match のリストに対して合致しなかった時、
match は nil を返します。
ワイルド・カード文字がパターンに無い時は、空リストが返ります。
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.
find、ref、
ref-all、replace において、
match は、関数オブジェクト(functor)パラメータとして、よく使われます。
また、リストに対する 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 は、使えません。
より強力な文字列合致には、
regex、
find、
find-all、
parse を使って下さい。
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.
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 は、リスト 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"
関連する関数
slice と
find も見て下さい。
See also the related functions
slice and
find.
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.
num-1 と num-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
整数に対してのみ動作させたい時は、
関数 % (percent sign) を使って下さい。
Use the % (percent sign)
function when working with integers only.
全ての式 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
行列matrix-A と matrix-B の行列の積を返します。
matrix-A が n 行 m 列で、
matrix-B が k 行 l 列なら
(m と k は等しい) 、
結果は、 n 行 l 列になります。
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を使って n 行 1 列の行列に変換しておく必要があります。
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.
行列演算子
det、
invert、
mat、
transpose も見て下さい。
See also the matrix operations det,
invert, mat
and transpose.
この機能は推奨されません、代わりに term を使って下さい。
(訳注:V10.2 から使えませんので、name がシンボル名に使えます。
以前のバージョンと互換性を持たせたい時は、
Deprecated functions and future changes を見て下さい。)
This function is deprecated, use term instead.
浮動小数点演算の結果が、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 の結果となります。
整数演算では、 NaN は 0 (zero) として扱われます。
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.
前もって待ち受け(listening)モードに置かれたソケット上の接続を受け入れます。
この接続の受信及び送信データ用に新規に作成されたソケット・ハンドルが返ります。
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/ ディレクトリにある
ファイル server と client の例も見て下さい。
See also the files server and client examples
in the examples/ directory of the source distribution.
前もって関数 net-connect か
関数 net-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.
第一構文では、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)
成功なら、関数 net-connect は、
ホストからの情報の送受信に使われるソケット番号を返します。
例では、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 buit-in function
get-url offering the same functionality.
オプションで、タイムアウト値 int-timeout がミリ秒単位で指定されます。
タイムアウト値無しでは、関数はポートを開くために 10秒待ちます。
タイムアウト値があると、関数は利用できないポートからの戻りを早めたり、遅くしたりできます。
次の例は、開いているポートを探すポート・スキャナーを示します:
Optionally a timeout value int-timeout in milli seconds
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 openport 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-connnect は、ポートが利用できない時、タイムアウト終了前に nil を返すかもしれません。
Win32 では、net-connnect は、nil で失敗する前に、
常にタイムアウトするまで待つでしょう。
On Unix net-connnect may return with nil before
the timeout expires, when the port is not available. On Win32
net-connect will always wait for the timout to expire before
failing with nil.
第二構文では、
UDP (User Datagram Protocol) 通信に適したソケットを作成するために、
第三パラメータ、文字列 "udp" または "u" が、
オプションの str-mode に指定されます。
UDP モードでは、net-connect は、リモート・ホストへの接続を試みません が、
ソケットを作成し、アドレスが指定されれば、それをリモート・アドレスに束縛します。
続いて net-send は、目標アドレスを含む UDP パケットを送信します。
net-send-to を使う時、
関数net-connect か net-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-listen か net-connect で "udp" オプションが使われた時、
関数 net-receive と net-receive-from が、両方とも使え、UDP 通信を実行します。
net-select と net-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.
第三パラメータ 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-peek か net-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 と net-receive は、
net-send-to や net-receive-from の代わりに使われます。
The net-send and
net-receive functions
can also be used instead of net-send-to
and net-receive-from.
第三パラメータ 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 は、実際には、受信側を待ち受けモードに置きません。
どちらかというと、ソケットを特殊 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-select あるいは net-peek が、
ノン・ブロッキング状態で通信が来たかどうかのチェックに使えます。
The net-select
or net-peek functions
can be used to check for
incoming communications
in a non-blocking fashion.
第三構文では、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-listen と net-accept を使って生成されています。
接続が確立された後は、関数 net-select、
net-send、
net-receive が、TCP/IP ストリーム通信に普通に使われます。
この接続のタイプは、同じファイル・システム上のプロセス間高速双方向通信チャンネルとして使われます。
この接続のタイプは、Win32 プラットフォーム では、利用できません。
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 Win32 platforms.
次の関数
net-accept、
net-connect、
net-eval、
net-listen、
net-lookup、
net-receive、
net-receive-udp、
net-select、
net-send、
net-send-udp、
net-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:
| no | description |
|---|---|
| 1 | Cannot open socket |
| 2 | DNS resolution failed |
| 3 | Not a valid service |
| 4 | Connection failed |
| 5 | Accept failed |
| 6 | Connection closed |
| 7 | Connection broken |
| 8 | Socket send() failed |
| 9 | Socket recv() failed |
| 10 | Cannot bind socket |
| 11 | Too many sockets in net-select |
| 12 | Listen failed |
| 13 | Badly formed IP |
| 14 | Select failed |
| 15 | Peek failed |
| 16 | Not a valid socket |
| 17 | Cannot unblock socket |
| 18 | Operation timed out |
| 19 | HTTP bad formed URL |
| 20 | HTTP file operation failed |
| 21 | HTTP transfer failed |
| 22 | HTTP invalid response from server |
| 23 | HTTP no response from server |
| 24 | HTTP document empty |
| 25 | HTTP error in header |
| 26 | HTTP 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-error と sys-error も見て下さい。
See also last-error and sys-error.
一つ以上の 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 式は、目標ノードの環境下でリモートに評価される文字列か式のどちらかに評価されます。
The expression in exp evaluates to either a string or an expression
which will be evaluated remotely in the environment of the target node.
リモート TCP/IP サーバーは、次のような方法で開始されます:
The remote TCP/IP servers are started in the following way:
newlisp -c -d 4711 & ; or with logging connections newlisp -l -c -d 4711 & ; communicate via Uix local domain socket newlisp -c /tmp/mysocket
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.
デーモン・モード -d は、newLISP を接続間の状態を保持するようにします。
接続間の状態保持を望まない時は、inetd daemon mode がより有利な状態を提供します。
インターネット inetd あるいは xinetd サービス・デーモンは、各クライアント接続毎に、一つの新規 newLISP プロセスを開始します。
これは、複数の接続でより高速なサービスを作り出します。
-d デーモン・モードでは、各クライアント要求(request)は、先行している要求(request)が終わるのを待たねばなりません。
このモードの正しい設定方法は、inetd daemon mode の章で見て下さい。
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.
第一構文で、net-eval は、一つのリモート newLISP サーバー・ノードに対してだけ会話(talk)し、
ホスト str-host にポート int-port で、式 exp を評価する要求(request)を送ります。
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 (net-eval "192.168.1.94" 4711 "(+ 3 4)") → 7 ; with timeout (net-eval "192.168.1.94" 4711 '(+ 3 4) 1) → nil ; timeout to 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 Win32) (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.
foo や myfunc の定義は、両方共、目標環境に存在しなければならないことに注意して下さい。
これは、前もって 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 remode 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-url や save (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 は、引数param を nil にして呼び出されます。
リモート・ノードの結果が全て受信されると、myhandler は、
リモート・ホスト名か IP 番号 とポートと結果の式からなるリストにセットされた param で呼び出されます。
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-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
インターネット・プロトコル・バージョン 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 で待ち受けるかしたなら、
関数net-accept、
net-select、
net-send、
net-receive、
net-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.
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 より低いポートを待ち受けること(listening)は、
スーパー・ユーザ・アクセスを要求する事に注意して下さい。
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")
第二構文では、 net-listen は、
str-file-path を使って名前付けられた local domain Unix socket を通して、
ローカル・ファイル・システム上のクライアントを待ち受けます(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)
local domain ファイル・システム・ソケットが、生成され、待受状態になっています。
クライアントは、同じ str-file-path を使って接続を試みます。
接続が関数net-select に受け入れられた後、
net-send と net-receive が、
TCP/IP ストリーム通信に普通に使われます。
この接続タイプは、同じファイル・システム上のプロセス間高速双方向通信チャンネルとして使えます。
この接続タイプは、Win32 プラットフォームでは、使えません。
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 Win32 platforms.
UDP (User Datagram Protocol) 通信に適したソケット一式を生成するために
第三パラメータとして、
オプション文字列 "udp" または "u" が、str-mode に指定されます。
この方法で作られたソケットは、TCP 通信にのみ使われる net-accept を使うこと無しに、
入力 UDPデータを待ち受けるのに net-receive-from で直接使えます。
net-receive-from 呼び出しは、
UDP データ・パケットが受信されるまで、ブロックされます。
代わりの方法として、
ノン・ブロッキング状態でデータが準備できたかどうかのチェックに
net-select か net-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")
一番目の例が、指定したネットワーク・アダプタを待ち受ける、
一方で、二番目の例が、デフォルト・アダプタを待ち受けます。
どちらの呼び出しも、引き続く関数
net-receive、
net-receive-from、
net-send-to、
net-select」、
net-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/client と examples/server を見て下さい。
For a working example, see the files
examples/client and examples/server
in the newLISP source distribution.
net-listen と "udp" オプションの代わりに、
関数net-receive-udp と
net-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-listen、
net-select、
net-peek は、ノン・ブロッキング読み出しを簡単にするのに使われます。
待ち受け/読み出しソケットが閉じられず、再び、続きの読み出しに使えます。
対照的に、net-receive-udp と net-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.
オプション文字列 str-mode に"multi" か "m" が指定されると、
net-listen は、マルチキャストに適切なソケットを返します。
この場合、str-ip-addr には、マルチキャスト・アドレス範囲 224.0.0.0 ~ 239.255.255.255 の中の一つが入ります。
net-listen は、マルチキャスト伝送を受信するアドレスとして str-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-peek か net-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 と net-receive は、
net-send-to と net-receive-from の
代わりに使われます。
The net-send
and net-receive functions
can be used instead of net-send-to
and net-receive-from.
BSDライクのプラットフォーム上で、
str-mode が "divert" に指定されたら、
int-port を divert ポートとして
divert ソケットが生成されます。
str-ip-addr の IP アドレスの内容は、無視されます。
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 specifed as an empty string. Only the int-port is
relevant and will be bound to the raw socket returned.
net-listen で divert オプションを使うためには、
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 ソケットは、divert ポートに迂回された全ての生ソケットを受け取ります。
また、パケットは 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.
divert ポートへのパケット迂回ルールは、
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 宣言文で生成され、返された
divert ソケット上の生パケットの読み書きに
関数 net-receive-from と
net-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 マニュアルで divert の項か、
設定ユーティリティ ipfw (BSDs) or ipchains (Linux) を見て下さい。
For more information see the Unix man pages for divert
and the ipfw (BSDs) or ipchains (Linux) configuration
utilities.
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.
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.
関数は、raw sockets インターフェイスを通して送信される
カスタム構成のネットワーク・パケットを許可します。
str-packet のパケットは、
TCP か UDP か ICMP ヘッダーのいずれかとオプション・データの続く
IP (Internet Protocol) ヘッダーで始まっていなければなりません。
newLISP は、スーパー・ユーザ特権で走っている必要があり、
この関数は、Mac OS X、Linux、その他の Unix オペレーティングシステムで、
かつ、IP v.4.でのみ利用可能です。
現在、net-packet は IPv4 のみであり、Mac OS X、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 Mac OS X,
Linux and other Unix operating systems and only for IPv4.
Currently net-packet is IPv4 only and has been tested on
MAC OS X, Linux and OpenBSD.
成功時、関数は送信バイト数を返します。
失敗時は、関数は nil を返し、
net-error と sys-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 contains zeros in the checksum fields,
net-packet will calculate and insert the correct checksums.
Already existing checksums stay untouched.
次の例は、UDP パケットを IP 番号 192.168.1.92 に注入します。
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.
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.
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.
この関数は、Unixベース・システム上でのみ利用可能で、スーパー・ユーザ・モードで走っていなければなりません。
例えば、Mac OS X か 他の BSD で newLISP の開始に sudo newlisp を使うとか、Linux の root ユーザとか。
ブロードキャスト・モードや
- (hyphen) または * (star) を使った範囲指定は、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 Mac OS X 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.
バージョン 10.1.7から、Mac OS X では、スーパー・ユーザ・モードは、要求されなくなりました。
Since version 10.1.7, superuser mode is not required on Mac OS X.
第一構文では、net-ping は、ICMP 64バイトのエコー要求(echo request)を、str-address で指定されたアドレスに送ります。
それがブロードキャスト・アドレスなら、ICMP パケットは、全てのサブネットで受信されます。
セキュリティ上の理由から、多くのコンピュータは、ICMP ブロードキャスト ping
(ICMP_ECHO)要求(request)に返信しないことに注意して下さい。
オプションのタイムアウト・パラメータは、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 は、batch mode で走ります。
このモードでは、一つのソケットのみが開かれますが、複数の 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.
ブロードキャストやバッチ・モードで待っている応答(response)の数を制限するために、
受信応答最大数を指定する追加の引数が、int-count に指定されます。
このパラメータの使えば、指定したタイムアウトより早く関数を戻せます。
与えられた応答数を受信すると、net-ping は、タイムアウト前でも戻ります。
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
→ ()
通常のアドレスや IP 番号またはホスト名と同様にブロードキャストまたは、バッチ・モードは、
一つの net-ping 文において、リスト中に 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 番号の最後のサブネット・オクテットに
ワイルドカード文字としての * (asterisk) を指定して始められることを示しています。
第四、第五行は、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.
ソケット 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-peek や net-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-receive は、wait-string に一致した文字か文字列を受信した後で、返ります。
wait-string は、sym-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)
(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 は、ノン・ブロッキング通信の設定で使われます。
int-socket のソケットは、
(共に "udp" オプションの)net-listen か net-connect によって、
予め開かれていなければなりません。
int-max-size は、受信される最大バイト数を指定します。
Linux/BSD 上では、それ以上受信されると、破棄されます。
Win32 上では、net-receive-from は nil を返し、ソケットを閉じます。
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 Win32, 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.
;; listen on port 1001 on 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 サーバーは、
いくつかのポートを待ち受け、ポーリングし、それらがデータを受信するように配給するように設定されます。
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.
この場合、送信側のアドレスとポートの情報を返さないので 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-udp や net-receive-udp を見て下さい。
For blocking short UDP transactions,
see the net-send-udp
and net-receive-udp functions.
ポート int-port 上の User Datagram Protocol (UDP) パケットを受信し、 int-maxsize バイト読み取ります。
int-maxsize バイトより多く受信した場合、Linux/BSD では、 int-maxsize を超えるバイトは、破棄され、
Win32 では、net-receive-udp は 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 Win32, 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-listen あるいは net-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.
一個以上のインターフェイス・カードを持つコンピュータ上で指定したアドレスを待ち受けるために、
インターフェイス 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 通信は、ノン・ブロッキング・データ交換を可能にする "udp" オプションで
net-listen または net-connect を
net-receive-from と net-send-to を一緒に使ってもセットアップされます。
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 は、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 で指定された時間待ち、
準備状態次第で true か nil を返します。
セレクト・ループ中、プログラムの他の部分は、実行可能です。
エラー発生時には、net-error がセットされます。
-1 が、int-micro-seconds に指定された時は、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 が使われている時は、いくつかの待ち受けと接続ソケットが監視され、複数の接続が処理されます。
ソケット・リストを使った時、net-select は、準備の整ったソケットのリストを返します。
続く例は、二つのソケットを待ち受け、その接続の受け入れとサービスを続けます:
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 userdefined 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.
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".
UDP か TCP/IP 通信のどちらかで使われます。
int-socket のソケットは、前もって、
関数net-connect か net-listen で、開かれていなければなりません。
開くのに使う関数は、
net-listen か net-connect は、"udp" オプションを使われると、UDP ソケットを生成するだけで、待ち受けや接続にも使われません。
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-send-to と一緒に net-connect を使う時、
関数の一つだけが、リモート・ホストを指定すべきです。
他方は、空の文字列でアドレスを切り離すべきです。
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-udp とnet-receive-udp を使って下さい。
For blocking short UDP transactions use net-send-udp
and net-receive-udp.
str-remotehost で指定されたホストと int-remoteport のポートに User Datagram Protocol (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 流派では、かなり少なくなります。
Mac OS X、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 Mac OS X, BSDs and Linux.
前もって、net-connect か net-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.
オプションとして、bool に、true か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 ネットワーク上の全てのノードに送信されます。
いくつかのオペレーティング・システムでは、
bool の true 無しのネットワーク・マスク 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 待ち受けとの通信にノン・ブロッキング状態で使われます。
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 は、
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"
アクティブな待ち受けや接続ソケットのリストを返します。
Returns a list of active listening and connection sockets.
コンテキスト context-source は、sym-context-target にコピーされます。
目標コンテキストが無いなら、 context-source にあるのと同じ名前の変数群とユーザ定義関数と持つ新コンテキストが作成されます
(訳注:ただし、デフォルト・ファンクタ は、目標コンテキスト名になります)。
目標コンテキストが、既に存在するなら、新規のシンボルと定義が付け加えられます。
存在するシンボルは、bool の式が nil 以外に評価される時のみ、
上書きされ、それ以外では、そのままの内容で残ります(訳注:bool 式次第で、デフォルト・ファンクタ も上書きされます)。
これは、コンテキスト・オブジェクトの mixins を可能にします。
new は、MAIN ではないターゲット・コンテキストを返します。
(訳注:mixins の意味するところは、日本語版 Wiki か、英語版 Wiki でどうぞ。)
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.
二行目は、MyCTX に CTX を併合します。
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)
例は、変数でコンテキストを参照し、
コンテキスト bar に foo を併合しています。
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.
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 は、長さ int-n のランダムかつ、
平均値 float-mean と 標準偏差 float-stdev で
継続的に分散された浮動小数点数のリストを返します。
内部のランダム生成は、関数 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 0 1) → 0.6630859375
均等に分散された数値用の関数 random や rand、
式のリストの中からランダムに評価するための 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.
exp が、nil か、空リスト () に評価されたなら、
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
現在の日付と時刻の情報を整数のリストで返します。
オプションのタイム・ゾーンのオフセットは、分単位で 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 (apply date-value (now)) → 1014834090
数値は、次のように表現されています:
The numbers represent the following date-time fields:
| format | description |
|---|---|
| 年 year | Gregorian calendar(グレゴリオ暦) |
| 月 month | (1–12) |
| 日 day | (1–31) |
| 時 hour | (0–23) UTC(協定世界時) |
| 分 minute | (0–59) |
| 秒 second | (0–59) |
| マイクロ秒 microsecond | (0–999999) OS-specific, millisecond resolution(OS の仕様によっては、ミリ秒単位の解像度) |
| 年間通算日 day of current year | Jan 1st is 1(一月一日が 1) |
| 週の曜日 day of current week | (1–7) starting Monday(月曜にから始まる) |
| タイムゾーンのオフセット(分単位) time zone offset in minutes | west of GMT(グリニッジ標準時から西回り) (訳注:(now (now 0 -2)) でタイムゾーンの現在の日時が返ります) |
| 夏時間の型 daylight savings time type | (0–6) on Linux/Unix or bias in minutes on Win32(Linux/Unix では (0–6)、Win32 では分単位のオフセット) |
二つ目の例は、協定世界時 (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 (zero) になります。
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 (zero) を返します
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:
| type | area |
|---|---|
| 0 | not on dst |
| 1 | USA style dst |
| 2 | Australian style dst |
| 3 | Western European dst |
| 4 | Middle European dst |
| 5 | Eastern European dst |
| 6 | Canada dst |
関数date、
date-list、
date-parse、
date-value、
time、
time-of-day も見て下さい。
See also the date,
date-list,
date-parse,
date-value,
time, and time-of-day functions.
固定利率 num-interest と支払額num-pmt で、
num-pv のローンを支払うために必要となる支払回数を計算します。
支払いが期間の終わりなら、int-type は、0 か省略し、
支払いが期間の最初なら、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.
関数 fv、
irr、
npv、
pmt、
pv も見て下さい。
See also the fv,
irr,
npv,
pmt,
and pv functions.
固定利率 num-interest で list-values の将来の投資額と配当のシリーズで投資の総現在価値を計算します。
投資額は、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.
関数 fv、
irr、
nper、
pmt、
pv も見て下さい。
See also the fv,
irr,
nper,
pmt,
and pv functions.
第一構文グループでは、nth は、
list, array, str の検出インデックスに
int-index を使って、インデックスで見つかった要素を返します。
Indexing elements of strings and lists も見て下さい。
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 の implicit indexing(暗黙のインデックス) 版は、newLISP 構文を壊すものではなく、
newLISP 構文の論理的拡張は、組込関数やラムダ式よりも、データ型で規定されると理解すべきことに注意して下さい。
s式の関数オブジェクト(functor)位置にあるリストは、続くインデックス引数を使った自己インデックス機能と解釈されます。
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 や
リストを変更する push と pop も見て下さい。
See also setf for modifying multidimensional lists and arrays and
push and pop for modifying lists.
式が nil、
空リスト ()、
空文字列 ""、
NaN (not a number)、
0 (zero) のいずれかに評価されるかどうかをチェックし、
その場合、true を返します。
それ以外の全ての場合で、null? は nil を返します。
述語 null? は、
filter や clean と連携して、
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?.
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)) trueNaN や INF の型は、浮動小数点数です。)
数値型を指定したテスト関数 float? や integer? も見て下さい。
See the functions float? and integer? to test for a specific number type.
整数値の偶奇をチェックします。
数値が 2 で割り切れないなら、それは奇数です。
int-number に浮動小数点数が渡された時は、
最初に小数部分が切り捨てられ、整数に変換されます。
Checks the parity of an integer number. If the number is not even divisable 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, divisable by 2.
str-path-file は、ファイル名で、
str-access-mode は、ファイル・アクセス・モードを指定する文字列です。
open は、それに続くファイルの読み書き操作で使われるファイル・ハンドルになる整数値を返します。
失敗時、open は、nil を返します。
アクセス・モード "write" は、ファイルが存在しない時は作成し、
存在するファイルには、長さ 0 (zero) バイトに切り詰めます。
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:
(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 (zero) にリセットするということに注意して下さい。
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).
オプション str-option として、"non-block" か "n" が、"read" や "write" オプションの後に指定されます。
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.
newLISP 上で 名前付きパイプを作成するには、
関数 exec か import を使って下さい:
To create a named pipe in newLISP,
use the exec or import function:
(exec "mkfifo myfifo") ;; or alternatively (import "/lib/libc.so.6" "mkfifo") (mkfifo "/tmp/myfifo" 0777)
これで、名前付きパイプは、open、
read、
writer を使ったファイルのように使われます。
The named pipe can now be used like a file with open,
read, and write.
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
newLISP が走っているオペレーティングシステム名の入っている組込定数です。
ostype is a built-in system constant
containing the name of the operating system
newLISP is running on.
ostype → "Win32"
次の文字列の中の一つが返ります:
"Linux", "BSD", "OSX", "Tru64Unix", "Solaris", "SunOS", "Win32", "OS/2"
One of the following strings is returned:
"Linux", "BSD", "OSX", "Tru64Unix", "Solaris", "SunOS", "Win32", 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.
一個以上の式群 (exp-1 ~ exp-n) を
フォーマット文字列 str-format で指定された
バイナリ・フォーマットにパックし、
文字列バッファ中のバイナリ構造体で返します。
対となる関数 unpack が、アンパックに使えます。
引数の式群は、list でも与えられます(訳注:第二構文)。
pack と unpack は、バイナリ・ファイルの読み書き
(read と write 参照)や、
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 定義のシンボルの時、
pack は struct で定義されたフォーマットを使います。
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.
次の文字が、str-format に使えます:
The following characters are used in str-format::
| format | description |
|---|---|
| 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 |
pack は、b、c、d、ld、lu フォーマットで渡された時、全ての浮動小数点を整数に変換します。
同様に、f と lf で渡された時、整数を浮動小数点に変換します。
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ビット・ポインタを表します。
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.
> と < 指定は、
パック及びアンパック時の little endian と big endian バイト順の切り替えに使用できます:
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.
関数 address、
get-int、
get-long、
get-char、
get-string、
unpack も見て下さい。
See also the address,
get-int,
get-long,
get-char,
get-string,
and unpack functions.
str-data の評価結果からくる文字列を文字列のトークンに分解し、リストにして返します。
str-break が無い時、parse は、newLISP内部解析ルールに従ってトークン化します。
トークン化のためには、文字列中に現れる文字列のみが str-break に
指定されるでしょう。
int-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 int-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.
(parse "hello how are you") → ("hello" "how" "are" "you") (parse "one:two:three" ":") → ("one" "two" "three") (parse "one--two--three" "--") → ("one" "two" "three") (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 (zero)で文字列を分解する
正規表現を示しています。
{ と } (左と右の波括弧) の代わりに、
ダブルクォートがパターン境界に使われます。
この場合、パターン内に、二重のバックスラッシュが使用される必要があります。
最後のパターンは、CSV (Comma Separated Values) ファイルの解析に使えます。
正規表現のオプション番号は、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 は、分離子(separator)周りの空フィールドを空文字列として返します:
parse will return empty fields
around separators
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 や
正規表現が使える関数
directory、
find、
find-all、
regex、
replace、
search も見て下さい。
Use the regex function
to break strings up
and the directory,
find,
find-all,
regex,
replace,
and search functions
for using regular expressions.
ファイル記述子で読み取り可能なバイト数を返します。
ファイル記述子が無効なら、nil を返します。
peek は、stdin のチェックにも使えます。
この関数は、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-peek が、net-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.
内部通信用パイプを作成し、read と write のハンドルをリストにして返します。
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.
固定金利 num-interest 、支払回数 num-periods 回のローンの支払い額を計算します。
num-future-value は、最後のローン額です(典型的には 0.0)。
期間の終わりに支払うなら、 int-type は 0 (zero) か int-type は 省略され、
期間の最初に支払うなら、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.
関数 fv、
irr、
nper、
npv、
pv も見て下さい。
See also the fv,
irr,
nper,
npv,
and pv functions.
pop を使って、リストから要素を、あるいは文字列から文字を取り去ることができます。
Using pop, elements can be removed from lists and characters from strings.
第一構文では、pop は、list を評価することで得られたリストから要素を取り出します。
第二パラメータが存在するなら、int-index の要素が取り出されます。
Indexing elements of strings and lists も見て下さい。
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 で指定されます。
この方法で、pop は、
ref やインデックスのリストを返す ref-all と一緒に容易に動作します。
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 100) → 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