Skip to content


Subversion checkout URL

You can clone with
Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

8039 lines (5495 sloc) 214.319 kb
.. We use docutils to produce the documentation. Docstrings are extracted
.. with pure-doc. Please see the pure-doc documentation for details.
.. This module is always the first in the library docs, so produce the
.. title here.
Pure Library Manual
.. Add all pertaining author and copyright information here.
:Author: Albert Graf <>
:Date: |date|
.. Add all global docutils declarations here.
.. role:: dfn(strong)
.. default-role:: dfn
.. |date| date::
.. |GPL| replace:: GNU General Public License
.. |FDL| replace:: GNU Free Documentation License
.. _FDL:
.. _GPL:
.. _Pure Manual: pure.html
Copyright (c) 2009-2010 by Albert Graf. This document is available under
the |FDL|_.
This manual describes the operations in the standard Pure library,
including the prelude and the other library modules which come bundled with
the interpreter.
このマニュアルは、 Pure 標準ライブラリに含まれる処理を解説しています。標準ライブラリは、インタープリタにバンドルされている prelude やその他ライブラリモジュールを含んでいます。
There is a companion to this manual, the `Pure Manual`_ which describes the
Pure language and the operation of the Pure interpreter.
このマニュアルには `Pure Manual`_ という相棒がいます。そちらでは Pure 言語そのものと Pure インタープリタの働きを解説しています。
.. Table of contents, switch on section numbering.
.. contents::
.. sectnum::
The prelude defines the basic operations of the Pure language. This
includes the basic arithmetic and logical operations, string, list and
matrix functions, as well as the support operations required to implement
list and matrix comprehensions. The string, matrix and record operations
are in separate modules strings.pure, matrices.pure and records.pure, the
primitive arithmetic and logical operations can be found in
primitives.pure. Note that since the prelude module gets imported
automatically (unless the interpreter is invoked with the ``--no-prelude``
option), all operations discussed in this section are normally available in
Pure programs without requiring any explicit import declarations.
prelude は Pure 言語の基本的な処理を定義します。ここに含まれるのは、基本的な数値演算と論理演算、文字列・リスト・マトリクス処理関数、さらにリスト内包とマトリクス内包の実装に必要な支援用処理です。文字列、マトリクス、レコードの各処理はそれぞれ string.pure 、 matrices.pure 、 records.pure にモジュールとして分けられており、プリミティブな数値と論理の処理は primitives.pure 内で見つかります。 prelude のモジュールは自動的にインポートされる(インタープリタが ``--no-prelude`` オプション付きで起動された場合は別)ので、このセクションで議論される処理は全て Pure プログラム内で普通に利用でき、明示的なインポート宣言は必要ないことを覚えておいて下さい。
.. raw:: html
<a name="true">
.. raw:: html
<a name="false">
.. _true:
.. _false:
The prelude also declares a signature of commonly used constant and
operator symbols. This includes the truth values ``true`` and ``false``.
These are actually just integers in Pure, but sometimes it's convenient to
refer to them using these symbolic constants. Note that if you also want to
use these on the left-hand side of equations, you still have to declare
them as ``nonfix`` symbols yourself, using a declaration like:
また、 prelude は共用定数シンボルと共用演算子シンボルの signature を宣言します。ここには真偽値の ``true`` と ``false`` が含まれます。 Pure における両者は、実際には単なる整数にすぎませんが、記号定数を使ってそれをそれらを参照するのが便利なこともしばしばあります。もし true と false を等式左辺で利用したい場合、あなたは自分で両者を ``nonfix`` シンボルとして宣言しなければならないことに注意して下さい。次のような宣言を使います::
nonfix false true;
In addition, the following special exception symbols are provided:
.. raw:: html
<a name="failed_cond">
.. raw:: html
<a name="failed_match">
.. raw:: html
<a name="stack_fault">
.. raw:: html
<a name="malloc_error">
.. _failed_cond:
.. _failed_match:
.. _stack_fault:
.. _malloc_error:
* Built-in exception values: ``failed_cond`` (failed conditional in guard
or if-then-else), ``failed_match`` (failed pattern match in lambda,
``case`` expression, etc.), ``stack_fault`` (not enough stack space,
``PURE_STACK`` limit exceeded) and ``malloc_error`` (memory allocation
* 組み込み例外値: ``failed_cond`` (ガードか if-then-else 内で失敗した条件)、 ``failed_match`` (ラムダや ``case`` 式などの中で失敗したパターンマッチ)、 ``stack_fault`` (十分なスタックサイズが無い、 ``PURE_STACK`` 制限を超えた)、 ``malloc_error`` (メモリ割り当てエラー)。
.. raw:: html
<a name="bad_list_value">
.. raw:: html
<a name="bad_tuple_value">
.. raw:: html
<a name="bad_string_value">
.. raw:: html
<a name="bad_matrix_value">
.. _bad_list_value:
.. _bad_tuple_value:
.. _bad_string_value:
.. _bad_matrix_value:
* Value mismatches a.k.a. dynamic typing errors: ``bad_string_value x``,
``bad_matrix_value x``, ``bad_list_value x``, ``bad_tuple_value x``.
These are thrown by some operations when they fail to find an expected
value of the corresponding type.
* 値のミスマッチ a.k.a. 動的型付けエラー: ``bad_string_value x``, ``bad_matrix_value x``, ``bad_list_value x``, ``bad_tuple_value x``. 予測される型に対応する値が見つからなかったとき、これらの例外がスローされます。
.. raw:: html
<a name="out_of_bounds">
.. _out_of_bounds:
* Index range exceptions: ``out_of_bounds`` is thrown by the index operator
``!`` if a list, tuple or matrix index is out of bounds.
* インデックス範囲の例外: リスト、タプル、マトリクスのインデックスが境界を越えている場合、 ``!`` 演算子は ``out_of_bounds`` 例外をスローします。
.. raw:: html
<a name="operators">
.. _operators:
Here's the list of predefined operator symbols. Note that the parser will
automagically give unary minus the same precedence level as the
corresponding binary operator.
infixl 1000 $$ ; // sequence operator 継起演算子
infixr 1000 $ ; // right-associative application 右結合の適用
infixr 1100 , ; // pair (tuple) ペア(タプル)
infix 1200 => ; // key=>value pairs ("hash rocket") key=>value ペア(「ハッシュロケット」)
infix 1300 .. ; // arithmetic sequences 等差数列
infixr 1400 || ; // logical or (short-circuit) 論理 or (短絡)
infixr 1500 && ; // logical and (short-circuit) 論理 and (短絡)
prefix 1600 ~ ; // logical negation 論理否定
infix 1700 < > <= >= == ~= ; // relations 関係演算子
infix 1700 === ~== ; // syntactic equality 統語上の等値〔syntactic equality〕
infixr 1800 : ; // list cons リスト cons
infix 1900 +: <: ; // complex numbers (cf. math.pure) 虚数(cf. math.pure)
infixl 2000 << >> ; // bit shifts ビットシフト
infixl 2100 + - or ; // addition, bitwise or 加法、 bitwise or
infixl 2200 * / div mod and ; // multiplication, bitwise and 乗法、 bitwise and
infixl 2200 % ; // exact division (cf. math.pure)
prefix 2300 not ; // bitwise not
infixr 2400 ^ ; // exponentiation 冪乗〔累乗〕
prefix 2500 # ; // size operator サイズ演算子
infixl 2600 ! !! ; // indexing, slicing インデックス、スライス
infixr 2700 . ; // function composition 関数合成
prefix 2800 ' ; // quote クォート
postfix 2900 & ; // thunk サンク
Basic Combinators
.. raw:: html
<a name="combinators">
.. raw:: html
<a name="$">
.. raw:: html
<a name=".">
.. _combinators:
.. _$:
.. _.:
The most important function combinators are ``$`` (right-associative
application) and ``.`` (function composition), which are also defined as
macros so that saturated calls of these are eliminated automatically.
最も重要な関数結合演算子は ``$`` (右結合適用)と ``.`` (関数合成)です。両者はマクロとしても定義されているので、これらを saturated call した場合には自動的に取り除かれます。例::
> foo $ bar 99;
foo (bar 99)
> ( 99;
foo (bar 99)
.. raw:: html
<a name="id">
.. raw:: html
<a name="cst">
.. _id:
.. _cst:
The customary identity and constant combinators from the combinatorial
calculus are also available, in Pure these are named ``id`` and ``cst``,
customary identity と定数結合子 from the combinatorial calculus はどちらも利用可能です。 Pure ではそれぞれ ``id`` と ``cst`` と名付けられています::
> map id (1..5);
> map (cst 0) (1..5);
.. raw:: html
<a name="void">
.. _void:
There's also a combinator ``void`` which is basically equivalent to ``cst
()``, but with the special twist that it is also defined as a macro
optimizing the case of "throwaway" list and matrix comprehensions. This is
useful if a comprehension is evaluated solely for its side effects. E.g.:
さらに ``void`` という結合子もあります。基本的には ``cst()`` と同等〔equivalent〕ですが、 but with the special twist that it is also defined as a macro optimizing the case of "throwaway" list and matrix comprehensions. これは、ある内包を副作用のためだけに評価したい際に役立ちます。例えば::
> using system;
> extern int rand();
> foo = void [printf "%d\n" rand | _ = 1..3];
> show foo
foo = do (\_ -> printf "%d\n" rand) (1..3);
> foo;
Note that the above list comprehension is actually implemented using |do|_
(instead of |map|_, which would normally be the case), so that the
intermediate list value of the comprehension is never constructed. This is
described in more detail in section `Optimization Rules`_ of the Pure
上のリスト内包が、実際には |do|_ を使って実装されて(通常は |map|_ を使うところですが)おり、その結果、内包の中間的なリスト値は決して構築されないことを覚えておいて下さい。この点は Pure Manual の `Optimization Rules`_ セクションで詳細に解説されています。
.. |do| replace:: ``do``
.. |map| replace:: ``map``
.. _Optimization Rules: pure.html#optimization-rules
In addition, Pure also provides the following combinators adopted from
さらに、 Pure は次のような結合子を Haskell から借用し、提供しています:
.. raw:: html
<a name="flip">
.. _flip:
* ``flip f`` swaps arguments of a binary function ``f``, e.g.:
* ``flip f`` は二項関数 ``f`` の引数を入れ替えます。例えば::
> map (flip (/) 2) (1..3);
This combinator is also used by the compiler to implement right operator
sections, which allows you to write the above simply as:
この結合子は、コンパイラが right operator sections を実装するのにも使われます。これにより、上の表現を次のようにシンプルな書き方にできます::
> map (/2) (1..3);
.. raw:: html
<a name="curry">
.. _curry:
* ``curry f`` turns a function ``f`` expecting a pair of values into a
curried function of two arguments:
* ``curry f`` は、値のペアを想定した関数 ``f`` を、カリー化された2引数の関数へ変化させます::
> using system;
> dowith (curry (printf "%d: %g\n")) (0..2) [0.0,2.718,3.14];
0: 0
1: 2.718
2: 3.14
.. raw:: html
<a name="uncurry">
.. _uncurry:
* Conversely, ``uncurry f`` turns a curried function ``f`` expecting two
arguments into a function processing a single pair argument:
* 反対に、 ``uncurry f`` は、カリー化された関数 ``f`` (2引数を想定)を、単一のペア引数を処理する関数へ変化させます::
> map (uncurry (*)) [(2,3),(4,5),(6,7)];
.. raw:: html
<a name="curry3">
.. raw:: html
<a name="uncurry3">
.. _curry3:
.. _uncurry3:
* ``curry3`` and ``uncurry3`` are defined analogously, but are used to work
with ternary functions.
* ``curry3`` と ``uncurry3`` も同じように定義されていますが、3引数の関数を処理するために使われます。
.. raw:: html
<a name="fix">
.. _fix:
* The (normal order) fixed point combinator ``fix`` allows you to create
recursive anonymous functions. It takes another function ``f`` as its
argument and applies ``f`` to ``fix f`` itself:
* The (normal order) 不動点結合子〔不動点コンビネータ〕 ``fix`` で、再帰的な無名関数を作ることができます。 ``fix`` はもう一つ関数 ``f`` を引数に取り、 ``f`` を ``fix f`` そのものに適用することができます::
> let fact = fix (\f n -> if n<=0 then 1 else n*f (n-1));
> map fact (1..5);
See |fixpoint|_ at Wikipedia for an explanation of how this magic works.
Just like in Haskell, ``fix`` can be used to produce least fixed points
of arbitrary functions. For instance:
Wikipedia の |fixpointja|_ 〔 |fixpoint|_ 〕の項で、この魔法がどのように動作するかの説明を参照してください。 Haskell と同じように、 ``fix`` を使って任意の関数の宰相不動点を計算することができます。具体的には::
> fix (cst bar);
> let xs = fix (1:);
> xs;
1:#<thunk 0x7fe537fe2f90>
> xs!!(0..10);
.. |fixpoint| replace:: Fixed point combinator
.. _fixpoint:
.. |fixpointja| replace:: 不動点コンビネータ
.. _fixpointja:
Lists and Tuples
.. raw:: html
<a name="lists">
.. raw:: html
<a name="tuples">
.. raw:: html
<a name="list size">
.. raw:: html
<a name="tuple size">
.. raw:: html
<a name="null">
.. raw:: html
<a name="reverse">
.. raw:: html
<a name="#">
.. raw:: html
<a name=":">
.. raw:: html
<a name=",">
.. raw:: html
<a name="!">
.. raw:: html
<a name="!!">
.. _lists:
.. _tuples:
.. _list size:
.. _tuple size:
.. _null:
.. _reverse:
.. _#:
.. _\::
.. _,:
.. _!:
.. _!!:
The prelude defines the list and tuple constructors (``x:y``, ``x,y``), as
well as equality (``==``) and inequality (``~=``) on these structures. (The
latter compare two lists or tuples by recursively comparing their members,
so ``==`` must be defined on the list or tuple members if you want to use
these operations.) It also provides the predicate ``null x`` which tests
whether ``x`` is the empty list or tuple, the function ``reverse x`` which
reverses a list or tuple, and the operators ``#x`` (size of a list or
tuple), ``x!i`` (indexing), ``x!!is`` (slicing) and ``x+y`` (list
concatenation). Note that there isn't a separate operation for
concatenating tuples, since the pairing operator already does this:
prelude はリストとタプルのコンストラクタ( ``x:y``, ``x,y`` )を定義するだけでなく、それらの構造に関する等値( ``==`` )と非等値( ``~=`` )も定義します(後者は、2つのリストまたはタプルについて、そのメンバーを再帰的に比較します。なので ``==`` でもそのような処理をしたければ ``==`` がリストやタプルのメンバーに対して働くよう定義しなければなりません)■要確認■。また prelude は predicate ``null x`` も提供します。これは ``x`` がリストやタプルが空であるかどうかチェックするものです。関数 ``reverse x`` はリストやタプルを反転します。ほかにも演算子 ``#x`` (リストとタプルのサイズ)、 ``x!i`` (インデックス〔indexing〕)、 ``x!!is`` (スライス)、 ``x+y`` (リスト連結)が提供されます。タプルを結合する独立した処理は存在しないことを覚えておいて下さい。ペアリング演算子がその役を果たすからです::
> (1,2,3),(10,9,8);
This works because the ``(,)`` constructor is associative in Pure and will
always produce right-recursive pairs. This also implies that tuples are
always flat in Pure and can't be nested; if you need this, you should use
lists instead. Also note that the empty tuple ``()`` acts as a neutral
element with respect to ``(,)``:
これが動作するのは、 Pure において ``(,)`` コンストラクタが結合的な性質を持つ〔is associative〕からであり、常に右再帰のペア〔right-recursive pairs〕を生み出します。したがって Pure においてタプルは常にフラットであり、入れ子にする〔=ネストする〕ことはできません。入れ子にする場合は代わりにリストを使って下さい。また、空のタプル ``()`` は ``(,)`` との関係において無色の要素〔a neutral element〕として振る舞います::
> (),(a,b,c);
> (a,b,c),();
.. raw:: html
<a name="key">
.. raw:: html
<a name="val">
.. _key:
.. _val:
The prelude also provides another special kind of pairs called "hash
pairs", which take the form ``key=>value``. These are used in various
contexts to denote key-value associations. The only operations on hash
pairs provided by the prelude are equality testing (which recursively
compares the components) and the functions ``key`` and ``val`` which
extract the components of a hash pair:
また prelude はもう一つ、「ハッシュペア」と呼ばれる特殊なペアを提供します。これは ``key=>value`` という形式をとります。ハッシュペアは様々な文脈において key-value の関連を示すために使われます。 ハッシュペアに対する処理で prelude が提供するものは多くなく、等値のテスト(構成要素を再帰的に比較)と、関数 ``key`` と ``val`` (ハッシュペアから構成要素を抜き出す)です::
> ("foo"=>99) == ("bar"=>99);
> key ("foo"=>99), val ("foo"=>99);
Note that in difference to the tuple operator ``(,)``, the "hash rocket"
``(=>)`` is non-associative, so nested applications *must* be
parenthesized, and ``(x=>y)=>z`` is generally *not* the same as
``x=>(y=>z)``. Also note that ``(,)`` has lower precedence than ``(=>)``,
so to include a tuple as key or value in a hash pair, the tuple must be
parenthesized, as in ``"foo"=>(1,2)`` (whereas ``"foo"=>1,2`` denotes a
tuple whose first element happens to be a hash pair).
タプル演算子 ``(,)`` と異なり、「ハッシュロケット」 ``(=>)`` は結合的な性質を持ちません〔is non-associative〕。そのためネストされた適用は *必ず* 丸括弧で囲われ *なければならず* 、 ``(x=>y)=>z`` は一般に ``x=>(y=>z)`` と同じ *ではありません* 。また、 ``(,)`` の優先度は ``(=>)`` よりも低いので、ハッシュペアのキーや値としてタプルを含めるには、タプルが丸括弧で囲われている必要があります。例えば ``"foo"=>(1,2)`` のようにです(これに対して ``"foo"=>1,2`` は、最初の要素がハッシュペアにされてしまったタプルを示すことになります)。
.. raw:: html
<a name="list concatenation">
.. raw:: html
<a name="+ (list)">
.. _list concatenation:
.. _+ (list):
Lists are the usual right-recursive aggregates, pretty much the same as in
Lisp or Prolog except that they use a Haskell-like syntax. In difference to
Haskell, list concatenation is denoted ``+``, and lists may contain an
arbitrary mixture of arguments, i.e., they are fully polymorphic:
リストは、よくある右結合の集合体〔right-recursive aggregates〕で、 Lisp や Prolog とよく似ていますが、 Haskell 的な構文を持っています。ただ Haskell と異なるのは、リスト結合を ``+`` で示すことと、リストが任意の混合的な引数〔an arbitrary mixture of arguments〕を含むことができること、すなわち完全に多態的〔fully polymorphic〕であることです::
> 1:2:3:[];
> [1,2,3]+[u,v,w]+[3.14];
Lists are `eager` in Pure by default, but they can also be made `lazy`, see
section `Lazy Evaluation and Streams`_ in the Pure Manual.
Pure におけるリストはデフォルトで `熱心` 〔 `eager` =先行評価〕ですが、また `怠惰` 〔 `lazy` =遅延評価〕とすることも可能です。詳しくは Pure Manual の `Lazy Evaluation and Streams`_ を参照して下さい。
.. _Lazy Evaluation and Streams: pure.html#lazy-evaluation-and-streams
.. raw:: html
<a name="arithmetic sequences">
.. raw:: html
<a name="..">
.. _arithmetic sequences:
.. _..:
Arithmetic sequences can be constructed with the infix ``..`` operator:
等差数列は挿入演算子 ``..`` を使って構築できます::
> 1..5;
> 1:3..11;
Note that the Pure syntax differs from Haskell in that there are no
brackets around the construct and a step width is indicated by specifying
the first two elements as ``x:y`` instead of ``x,y``. Also, to specify
infinite sequences you have to use an infinite upper bound (``inf`` or
Pure の構文は Haskell のそれと以下の点で異なるので、注意して下さい。構造の前後にブラケットはありません。最初の2要素を ``x,y`` の代わりに ``x:y`` とすることで、数列のステップ幅を指定できます。また、無限数列の特性を持たせるには、無限大の上限( ``inf`` または ``-inf`` を使う必要があります::
> 1:3..inf;
1:#<thunk 0x7f696cd2dbd8>
> -1:-3..-inf;
-1:#<thunk 0x7f696cd2fde8>
The lower bounds of an arithmetic sequence must always be finite.
.. raw:: html
<a name="sort">
.. _sort:
Non-lazy lists can be sorted using the ``sort`` function, which provides an
interface to the C ``qsort()`` routine, please see your local qsort(3)
documentation for details. An order predicate ``p`` is specified as the
first argument, which must return a nonzero integer to indicate that its
first argument is "less than" its second argument. Example:
遅延評価でないリストは ``sort`` 関数を使ってソートできます。この関数は C の ``qsort()`` ルーチンへのインターフェースを提供します。詳しくは各自のローカルにある qsort(3) のドキュメントを参照して下さい。順序 predicate である ``p`` が ``sort`` の最初の引数として指定されます。この順序 predicate は、非ゼロの整数を返すことで、最初の引数が2番目の引数「よりも小さい」〔its first argument is "less than" its second argument〕ことを示します。例::
> sort (>) (1..10);
> sort (<) ans;
.. raw:: html
<a name="list">
.. raw:: html
<a name="tuple">
.. _list:
.. _tuple:
You can convert between (finite) lists and tuples using the ``list`` and
``tuple`` operations:
``list`` と ``tuple`` 処理を使って、(有限の)リストとタプルを相互に変換できます::
> tuple (1..5);
> list (a,b,c);
The ``list`` function can also be used to turn a finite lazy list into an
eager one:
``list`` 関数は、有限な遅延評価リストを先行評価のリストへと変えることもできます::
> list $ take 10 (-1:-3..-inf);
You can also achieve the same effect somewhat more conveniently by slicing
a finite part from a stream (see below):
> (-1:-3..-inf)!!(0..9);
.. raw:: html
<a name="stream">
.. _stream:
Conversely, it is also possible to convert a list to a stream:
> stream (1..10);
1:#<thunk 0x7fe537fe2b58>
This might appear a bit useless at first sight, since all elements of the
stream are in fact already known. However, this operation then allows you
to apply other functions to the list and have them evaluated in a lazy
.. raw:: html
<a name="list indexing">
.. raw:: html
<a name="tuple indexing">
.. _list indexing:
.. _tuple indexing:
Indexing of lists and tuples is always zero-based (i.e., indices run from
``0`` to ``#x-1``), and an exception will be raised if the index is out of
リストとタプルのインデックス参照はゼロベース(つまり、インデックスは ``0`` から ``#x-1`` の範囲)です。また、インデックスが境界を越えている場合は例外が発生します::
> [1,2,3]!2;
> [1,2,3]!4;
<stdin>, line 34: unhandled exception 'out_of_bounds' while evaluating
.. raw:: html
<a name="list slicing">
.. raw:: html
<a name="tuple slicing">
.. _list slicing:
.. _tuple slicing:
The slicing operator ``!!`` takes a list or tuple and a list of indices and
returns the list or tuple of the corresponding elements, respectively.
Indices which are out of the valid range are silently ignored:
スライス演算子 ``!!`` は、リストまたはタプルと、〔複数の〕インデックスのリストを取り、相応する要素のリストまたはタプルをそれぞれ返します。適切な範囲の外に出た分のインデックスは黙って無視されます::
> (1..5)!!(3..10);
> (1,2,3,4,5)!!(3..10);
Indices can actually be specified in any order, so that you can retrieve
any permutation of the members, also with duplicates. E.g.:
> (1..5)!![2,4,4,1];
This is less efficient than the case of contiguous index ranges (which is
optimized so that it always works in linear time), because it requires
repeated traversals of the list for each index. For larger lists you should
hence use vectors or matrices instead, to avoid the quadratic complexity.
.. |catmap| replace:: ``catmap``
(The prelude actually implements the slicing operation in a fairly generic
way, so that it works with any kind of container data structure which
defines ``!`` in such a manner that it throws an exception when the index
is out of bounds. It also works with any kind of index container that
implements the |catmap|_ operation.)
(実際には、 prelude はスライス処理を総称的な〔=ジェネリックな〕方法で行っています。■なので、あらゆる種類のコンテナデータ型に対して適切に動作しますが、ただし ``!`` を、境界外のインデックスに対して例外を投げるよう定義している必要があります。■また、 |catmap|_ 処理を実装しているあらゆる種類のインデックスコンテナに対しても動作します)
List Functions
This mostly comes straight from the Q prelude which in turn was based on
the first edition of the Bird/Wadler book, and is very similar to what you
can find in the Haskell prelude. Some functions have slightly different
names, though, and of course everything is typed dynamically.
リスト関数は Q 言語の prelude をほぼそのまま踏襲しており、その Q 言語の prelude は Bird/Wadler 本 [#]_ の初版を基礎としており、 Haskell の prelude で定義されているものとよく似ています。関数のいくつかは少し違った名前を持っていますが、もちろん動的に型付けされます。
.. [#] 訳注: Richard Bird & Philip Wadler, *Introduction to Functional Programming*, ISBN 978-0-13-484189-2, Prentice Hall, 1988. のことを指すと思われる。ちなみに 1998 年刊の第2版(978-0-130484346-9)はタイトルを *Introduction to Functional Programming using Haskell* と改め、 Bird の単著として刊行されている。
Common List Functions
.. raw:: html
<a name="any">
.. _any:
``any p xs``
tests whether the predicate ``p`` holds for any of the members of ``xs``
predicate ``p`` が ``xs`` のメンバーのいずれか1つでも保持しているかどうかをテストします。
.. raw:: html
<a name="all">
.. _all:
``all p xs``
tests whether the predicate ``p`` holds for all of the members of ``xs``
predicate ``p`` が ``xs`` のメンバーの全てを保持しているかどうかをテストします。
.. raw:: html
<a name="cat">
.. _cat:
.. |cat| replace:: ``cat``
``cat xs``
concatenate a list of lists
.. raw:: html
<a name="catmap">
.. _catmap:
``catmap f xs``
convenience function which combines |cat|_ and |map|_; this is also used
to implement list comprehensions
|cat|_ と |map|_ を組み合わせた便利な関数。リスト内包を実装するのにも使われます。
.. raw:: html
<a name="do">
.. _do:
``do f xs``
apply ``f`` to all members of ``xs``, like |map|_, but throw away all
intermediate results and return ``()``
``f`` を ``xs`` の全メンバーに適用します。 |map|_ と似ていますが、中間段階の結果をすべて捨てて ``()`` を返します。
.. raw:: html
<a name="drop">
.. _drop:
``drop n xs``
remove ``n`` elements from the front of ``xs``
``xs`` の要素を先頭から ``n`` 個分除去します。
.. raw:: html
<a name="dropwhile">
.. _dropwhile:
``dropwhile p xs``
remove elements from the front of ``xs`` while the predicate ``p`` is
predicate ``p`` が満たされるまで ``xs`` の先頭から要素を除去していきます。
.. raw:: html
<a name="filter">
.. _filter:
``filter p xs``
return the list of all members of ``xs`` satisfying the predicate ``p``
``xs`` のメンバーのうち predicate ``p`` を満たすものをすべて返します。
.. raw:: html
<a name="foldl">
.. _foldl:
``foldl f a xs``
accumulate the binary function ``f`` over all members of ``xs``,
starting from the initial value ``a`` and working from the front of the
list towards its end
二項関数 ``f`` を ``xs`` の全メンバーに対して集積的に適用〔accumulate〕します。初期値を ``a`` として、リストの先頭から末尾へと適用していきます。
.. raw:: html
<a name="foldl1">
.. _foldl1:
``foldl1 f xs``
accumulate the binary function ``f`` over all members of ``xs``,
starting from the value ``head xs`` and working from the front of the
list towards its end; ``xs`` must be nonempty
二項関数 ``f`` を ``xs`` の全メンバーに対して集積的に適用します。 ``head xs`` 〔 xs の先頭要素〕の値から始めて、リストの先頭から末尾へと適用していきます。 ``xs`` が空であってはいけません。
.. raw:: html
<a name="foldr">
.. _foldr:
``foldr f a xs``
accumulate the binary function ``f`` over all members of ``xs``,
starting from the initial value ``a`` and working from the end of the
list towards its front
二項関数 ``f`` を ``xs`` の全メンバーに対して集積的に適用します。初期値を ``a`` として、リストの末尾から先頭へと適用していきます。
.. raw:: html
<a name="foldr1">
.. _foldr1:
``foldr1 f xs``
accumulate the binary function ``f`` over all members of ``xs``,
starting from the value ``last xs`` and working from the end of the
list towards its front; ``xs`` must be nonempty
二項関数 ``f`` を ``xs`` の全メンバーに対して集積的に適用します。 ``last xs`` の値〔 xs の末尾要素〕から始まり、リストの末尾から先頭へと適用していきます。 ``xs`` が空であってはいけません。
.. raw:: html
<a name="head">
.. _head:
``head xs``
return the first element of ``xs``; ``xs`` must be nonempty
``xs`` の先頭要素を返します。 ``xs`` が空であってはいけません。
.. raw:: html
<a name="index">
.. _index:
``index xs x``
search for an occurrence of ``x`` in ``xs`` and return the index of the
first occurrence, if any, ``-1`` otherwise
``xs`` の中から ``x`` の出現を探し、見つかった場合には最初の出現位置のインデックスを、見つからない場合は ``-1`` を返します。
Note: This uses equality (``==``) to decide whether a member of ``xs`` is
an occurrence of ``x``, so ``==`` must have an appropriate definition on
the list members.
注意:この関数は等値演算子( ``==`` )を使って ``xs`` のあるメンバーが ``x`` であるかどうかを決定します。そのため ``==`` はリストメンバーに対して適切に定義されていなければなりません。
.. raw:: html
<a name="init">
.. _init:
``init xs``
return all but the last element of ``xs``; ``xs`` must be nonempty
``xs`` の最後の要素を除いた全要素を返します。 ``xs`` が空であってはいけません。
.. raw:: html
<a name="last">
.. _last:
``last xs``
return the last element of ``xs``; ``xs`` must be nonempty
``xs`` の末尾要素を返します。 ``xs`` が空であってはいけません。
.. raw:: html
<a name="listmap">
.. _listmap:
``listmap f xs``
convenience function which works like |map|_, but also deals with matrix
and string arguments while ensuring that the result is always a list;
this is primarily used to implement list comprehensions
|map|_ のように動作する便利な関数です。マトリクスとリストを引数として扱えますが、結果は常にリストとして返されます。主にリスト内包を実装するために使われます。
.. raw:: html
<a name="map">
.. _map:
``map f xs``
apply ``f`` to each member of ``xs``
``f`` を ``xs`` の各メンバーに適用します。
.. raw:: html
<a name="scanl">
.. _scanl:
``scanl f a xs``
accumulate the binary function ``f`` over all members of ``xs``,
as with ``foldl``, but return all intermediate results as a list
二項関数 ``f`` を ``xs`` の全メンバーに対して、 ``foldl`` を使った場合と同じように集積的に適用しますが、中間段階の結果全てをリストとして返します。
.. raw:: html
<a name="scanl1">
.. _scanl1:
``scanl1 f xs``
accumulate the binary function ``f`` over all members of ``xs``,
as with ``foldl1``, but return all intermediate results as a list
二項関数 ``f`` を ``xs`` の全メンバーに対して、 ``foldl1`` を使った場合と同じように集積的に適用しますが、中間段階の結果全てをリストとして返します。
.. raw:: html
<a name="scanr">
.. _scanr:
``scanr f a xs``
accumulate the binary function ``f`` over all members of ``xs``,
as with ``foldr``, but return all intermediate results as a list
二項関数 ``f`` を ``xs`` の全メンバーに対して、 ``foldlr`` を使った場合と同じように集積的に適用しますが、中間段階の結果全てをリストとして返します。
.. raw:: html
<a name="scanr1">
.. _scanr1:
``scanr1 f xs``
accumulate the binary function ``f`` over all members of ``xs``,
as with ``foldr1``, but return all intermediate results as a list
二項関数 ``f`` を ``xs`` の全メンバーに対して、 ``foldlr1`` を使った場合と同じように集積的に適用しますが、中間段階の結果全てをリストとして返します。
.. raw:: html
<a name="sort (list)">
.. _sort (list):
``sort p xs``
Sorts the elements of the list ``xs`` in ascending order according to the
given predicate ``p``, using the C ``qsort`` function. The predicate
``p`` is invoked with two arguments and should return a truth value
indicating whether the first argument is "less than" the second. (An
exception is raised if the result of a comparison is not a machine
リスト ``xs`` の要素を predicate ``p`` に従って昇順にソートします。ソートには C の ``qsort`` 関数が使われます。 predicate ``p`` 2引数とともに呼び出され、第1引数が第2引数「よりも小さい」場合に真を返すことが想定されます(比較の結果が machine int ではない場合、例外が起こされます)。
.. raw:: html
<a name="tail">
.. _tail:
``tail xs``
return all but the first element of ``xs``; ``xs`` must be nonempty
``xs`` の最初の要素を除いた全要素を返します。 ``xs`` が空であってはいけません。
.. raw:: html
<a name="take">
.. _take:
``take n xs``
take ``n`` elements from the front of ``xs``
``xs`` の先頭から ``n`` 個分の要素を取得します。
.. raw:: html
<a name="takewhile">
.. _takewhile:
``takewhile p xs``
take elements from the front of ``xs`` while the predicate ``p`` is
``xs`` の先頭から、 predicate ``p`` が満たされている限り要素を取得します。
List Generators
Some useful (infinite) list generators, as well as some finite (and eager)
variations of these. The latter work like a combination of ``take`` or
``takewhile`` and the former, but are implemented directly for better
いくつかの便利な(無限)リスト生成関数と、そのバリエーションであるいくつかの有限(かつ先行評価)リスト生成関数です。後者は ``take`` や ``takewhile`` を前者と組み合わせたように動作しますが、直接的に実装されているのでもっと効率的です。
.. raw:: html
<a name="cycle">
.. _cycle:
``cycle xs``
cycles through the elements of the nonempty list ``xs``, ad infinitum
空でないリスト ``xs`` の要素を無限に循環させます。
.. raw:: html
<a name="cyclen">
.. _cyclen:
``cyclen n xs``
eager version of ``cycle``, returns the first ``n`` elements of
``cycle xs``
``cycle`` 関数の先行評価版で、 ``cycle xs`` の先頭から ``n`` 個分の要素を返します。
.. raw:: html
<a name="iterate">
.. _iterate:
``iterate f x``
returns the stream containing ``x``, ``f x``, ``f (f x)``, etc.,
ad infinitum
``x``, ``f x``, ``f (f x)`` 等々を無限に含むストリームを返します。
.. raw:: html
<a name="iteraten">
.. _iteraten:
``iteraten n f x``
eager version of ``iterate``, returns the first ``n`` elements of
``iterate f x``
``iterate`` の先攻評価版で、 ``iterate f x`` の先頭から ``n`` 個分の要素を返します。
.. raw:: html
<a name="iterwhile">
.. _iterwhile:
``iterwhile p f x``
another eager version of ``iterate``, returns the list of all elements
from the front of ``iterate f x`` for which the predicate ``p`` holds
``iterate`` のもう一つの先攻評価版で、 ``iterate f x`` の先頭から、 predicate ``p`` を満たしている限り、全要素をリストとして返します。■要確認■
.. raw:: html
<a name="repeat">
.. _repeat:
``repeat x``
returns an infinite stream of ``x``\ s
``x`` を要素とする無限のストリームを返す [#]_ 。
.. [#] 訳注: cycle とは異なり、リストのリストとなる。 x が [0,1,2] なら [[0,1,2],[0,1,2], ... ]
.. raw:: html
<a name="repeatn">
.. _repeatn:
``repeatn n x``
eager version of ``repeat``, returns a list with ``n`` ``x``\ s
``repeat`` の先攻評価版で、 ``n`` 個の ``x`` を持つリストを返します。
Zip and Friends
Zip と仲間たち
.. raw:: html
<a name="unzip">
.. _unzip:
``unzip xys``
takes a list of pairs to a pair of lists of corresponding elements
.. raw:: html
<a name="unzip3">
.. _unzip3:
``unzip3 xyzs``
``unzip`` with triples
``unzip`` の3要素版です。
.. raw:: html
<a name="zip">
.. _zip:
``zip xs ys``
return the list of corresponding pairs ``(x,y)`` where ``x`` runs
through the elements of ``xs`` and ``y`` runs through the elements
of ``y``
対応するペア ``(x,y)`` のリストを返します。このとき ``x`` には ``xs`` の要素が順に入り、 ``y`` には ``ys`` の要素が順に入ります。
.. raw:: html
<a name="zip3">
.. _zip3:
``zip3 xs ys zs``
``zip`` with three lists, returns a list of triples
リスト3つに対する ``zip`` 関数で、3要素タプルのリストを返します。
.. raw:: html
<a name="zipwith">
.. _zipwith:
``zipwith f xs ys``
apply the binary function ``f`` to corresponding elements of ``xs``
and ``ys``
二項関数 ``f`` を、リスト ``xs`` と ``ys`` の対応する要素に適用します。
.. raw:: html
<a name="zipwith3">
.. _zipwith3:
``zipwith3 f xs ys zs``
apply the ternary function ``f`` to corresponding elements of ``xs``,
``ys`` and ``zs``
参考関数 ``f`` を、 ``xs`` と ``ys`` と ``zs`` の対応する要素に適用します。
Pure also has the following variations of ``zipwith``/``zipwith3`` which
throw away all intermediate results and return ``()``. That is, these work
like |do|_ but pull arguments from two or three lists, respectively:
また Pure は次のような ``zipwith``/``zipwith3`` の派生版を提供します。この派生版は中間段階の結果をすべて破棄し、 ``()`` を返します。つまり、これらは |do|_ と同じように動作しますが、それぞれ2つまたは3つのリストから引数を引き出します:
.. raw:: html
<a name="dowith">
.. _dowith:
``dowith f xs ys``
apply the binary function ``f`` to corresponding elements of ``xs``
and ``ys``, return ``()``
2項関数 ``f`` を ``xs`` と ``ys`` の対応する要素に適用し、 ``()`` を返します。
.. raw:: html
<a name="dowith3">
.. _dowith3:
``dowith3 f xs ys zs``
apply the ternary function ``f`` to corresponding elements of ``xs``,
``ys`` and ``zs``, return ``()``
3項関数 ``f`` を ``xs`` と ``ys`` と ``zs`` の対応する要素に適用し、 ``()`` を返します。
String Functions
.. raw:: html
<a name="strings">
.. _strings:
Pure strings are null-terminated character strings encoded in UTF-8, see
the `Pure Manual`_ for details. The prelude provides various operations on
strings, including a complete set of list-like operations, so that strings
can be used mostly as if they were lists, although they are really
implemented as C character arrays for reasons of efficiency. Pure also has
some powerful operations to convert between Pure expressions and their
string representation, see `Eval and Friends`_ for those.
Pure の文字列は、 UTF-8 でエンコードされ、ヌル文字を終端とする character strings です。詳しくは `Pure Manual`_ を参照して下さい。 prelude は文字列に対する様々な処理を提供します。これにはリスト的な処理の完全なセットが含まれているので、文字列をあたかもリストであるかのように使うことができます。ただし、効率を理由として、実際には C の文字配列として実装されています。また、 Pure は Pure 式とその文字列 representation を相互変換する強力な処理をいくつか持っています。これについて詳しいことは `Eval and Friends`_ を参照して下さい。
Basic String Functions
.. raw:: html
<a name="string concatenation">
.. raw:: html
<a name="string indexing">
.. raw:: html
<a name="string slicing">
.. raw:: html
<a name="+ (string)">
.. raw:: html
<a name="! (string)">
.. raw:: html
<a name="!! (string)">
.. _string concatenation:
.. _string indexing:
.. _string slicing:
.. _+ (string):
.. _! (string):
.. _!! (string):
Concatenation, indexing and slicing works just like with lists:
> "abc"+"xyz";
> let s = "The quick brown fox jumps over the lazy dog.";
> s!5;
> s!!(20..24);
.. raw:: html
<a name="string size">
.. raw:: html
<a name="null (string)">
.. raw:: html
<a name="# (string)">
.. _string size:
.. _null (string):
.. _# (string):
Checking for empty strings and determining the size of a string also works
as expected:
> null "";
> null s;
> #s;
You can search for the location of a substring in a string, and extract a
substring of a given length:
.. raw:: html
<a name="index (string)">
.. _index (string):
``index s u``
Returns the (zero-based) index of the first occurrence of the substring
``u`` in ``s``, or -1 if ``u`` is not found in ``s``.
``s`` の中にサブ文字列 ``u`` が最初に現れるインデックス位置(ゼロから始まる)を返します。 ``s`` 内に ``u`` が見つからない場合は ``-1`` を返します。
.. raw:: html
<a name="substr">
.. _substr:
``substr s i n``
Extracts a substring of (at most) ``n`` characters at position ``i`` in
``s``. This takes care of all corner cases, adjusting index and number of
characters so that the index range stays confined to the source string.
``s`` 内の位置 ``i`` から(少なくとも) ``n`` 文字分のサブ文字列を抽出します。この関数はインデックスと文字数を調節して元の文字列の範囲内におさめるので、あらゆるレアで厄介なケースも面倒を見てくれます。■要確認■
> index s "jumps";
> substr s 20 10;
"jumps over"
Note that Pure doesn't have a separate type for individual characters.
Instead, these are represented as strings ``c`` containing exactly one
(UTF-8) character (i.e., ``#c==1``). It is possible to convert such single
character strings to the corresponding integer character codes, and vice
Pure は個々の文字のための独立した型を持たないことを覚えておいて下さい。その代わり、〔以下の説明において〕個々の文字は文字列型 ``c`` として表されます。これは厳密に一つだけ( UTF-8 の)文字を含んでいます(すなわち ``$c==1`` )。このような単独文字変数〔single character strings〕は、それに対応する文字コード整数へ変換することも、またその逆も可能です:
.. raw:: html
<a name="ord">
.. _ord:
``ord c``
Ordinal number of a single character string ``c``. This is the
character's code point in the Unicode character set.
単独文字変数 ``c`` の ordinal number です。 Unicode 文字集合におけるその文字のコードポイントとなります。
.. raw:: html
<a name="chr">
.. _chr:
``chr n``
Converts an integer back to the character with the corresponding code
.. raw:: html
<a name="character arithmetic">
.. _character arithmetic:
In addition, the usual character arithmetic works, including arithmetic
sequences of characters, so that you can write stuff like the following:
> "a"-"A";
> "u"-32;
> "a".."k";
Strings are also ordered lexicographically based on their character codes:
文字列は文字コードの lexicographically based で順序づけることもできます::
> "awe">"awesome";
> "foo">="bar";
For convenience, the prelude provides the following functions to convert
between strings and lists (or other aggregates) of characters.
便宜のため、 prelude は次のような関数を提供し、文字列と文字のリスト(や他の文字の集合物〔aggregates〕)とを相互変換できるようにしています。
.. raw:: html
<a name="chars">
.. raw:: html
<a name="list (string)">
.. _chars:
.. _list (string):
``chars s``, ``list s``
Convert a string ``s`` to a list of characters.
文字列 ``s`` を文字リストへ変換します。
.. raw:: html
<a name="tuple (string)">
.. raw:: html
<a name="matrix (string)">
.. _tuple (string):
.. _matrix (string):
``tuple s``, ``matrix s``
Convert a string ``s`` to a tuple or (symbolic) matrix of characters,
文字列 ``s`` をそれぞれ、タプルへ、また文字列の(記号)マトリクスへと変換します。
.. raw:: html
<a name="strcat">
.. _strcat:
``strcat xs``
Concatenate a list ``xs`` of strings (in particular, this converts a
list of characters back to a string).
文字列型を要素とするリスト ``xs`` を結合します(特に文字のリストを文字列へと戻す場合によく使います)。
.. raw:: html
<a name="string">
.. _string:
``string xs``
Convert a list, tuple or (symbolic) matrix of strings to a string.
In the case of a list, this is synonymous with ``strcat``, but it also
works with the other types of aggregates.
文字列型を要素に持つリスト、タプル、(記号)マトリクスを、1つの文字列へ変換します。リストを指定した場合は ``strcat`` とまったく同じ動作となりますが、この関数は他種の集合物を扱うこともできます。
For instance:
> list "abc";
> string ("a".."z");
The following functions are provided to deal with strings of "tokens"
separated by a given delimiter string.
.. raw:: html
<a name="split">
.. _split:
``split delim s``
Splits ``s`` into a list of substrings delimited by ``delim``.
``s`` を、 ``delim`` を境界としたサブ文字列のリストに切り分けます。
.. raw:: html
<a name="join">
.. _join:
``join delim xs``
Joins the list of strings ``xs`` to a single string, interpolating the
given ``delim`` string.
文字列のリスト ``xs`` を1つの文字列へと、間に ``delim`` 文字列を挿入しつつ、つなぎ合わせます。
> let xs = split " " s; xs;
> join ":" xs;
We mention in passing here that more elaborate string matching, splitting
and replacement operations based on regular expressions are provided by the
system module, see `System Interface`_.
ここで述べておくべきは、正規表現を基礎として文字列のマッチング、切り分け〔splitting〕、置換を行うもっと精巧な処理が、システムモジュールにより提供されているということです。 `System Interface`_ を参照。
If that isn't enough already, most generic list operations carry over to
strings in the obvious way, treating the string like a list of characters.
(Some operations will actually return character lists in that case, so you
might have to apply ``string`` explicitly to convert these back to a
string.) For instance:
それでもまだ不十分なら、総称的なリスト処理のほとんどを文字列処理へと■明示的な方法で■持ち込むことができます。つまり、文字列を文字のリストのように扱うわけです。(このようなケースで、いつかの処理は実際に文字のリストを返します。そのため ``string`` を明示的に適用し、そのリストを文字列型へ変換して戻してやる必要があります)。例えば::
> filter (>="k") s;
> string $ map pred "ibm";
List comprehensions can draw values from strings, too:
> string [x+1 | x="HAL"];
Low-Level Operations
The following routines are provided by the runtime to turn raw C ``char*``
pointers (also called `byte strings` in Pure parlance, to distinguish them
from Pure's "cooked" UTF-8 string values) into corresponding Pure
strings. Normally you don't have to worry about this, because the C
interface already takes care of the necessary marshalling, but in some
low-level code these operations are useful. Also note that here and in the
following, the ``cstring`` routines also convert the string between the
system encoding and Pure's internal UTF-8 representation.
次のルーチンはランタイムにより提供されているもので、生の C ``char*``
ポインタ( Pure 用語では `バイト文字列` 〔 `byte strings` 〕と呼ばれることがあります。
Pure の「調理済み」 UTF-8 文字列値と区別するための用語です)を、それに応じた
Pure 文字列へと変えてくれます。通常は C インターフェースが必要なマーシャリングの面倒を見てくれるのでこのことについて心配する必要はありませんが、ある種の低レベルコードではこの処理が役に立ちます。また、■ここと次■においては、
``cstring`` ルーチンでも文字列をシステムエンコーディングと Pure の内部
UTF-8 表現との間で相互変換できることも覚えておいて下さい。
.. raw:: html
<a name="string (pointer)">
.. raw:: html
<a name="cstring">
.. _string (pointer):
.. _cstring:
``string s``, ``cstring s``
Convert a pointer ``s`` to a Pure string. ``s`` must point to a
null-terminated C string. These routines take ownership of the original
string value, assuming it to be ``malloc``\ ed, so you should only use
these for C strings which are specifically intended to be freed by the
ポインタ ``s`` を Pure 文字列へ変換します。 ``s`` はヌル文字を終端とする
C 文字列でなければなりません。これらのルーチンは元々の文字列値〔original
string value〕の所有権を引き取り、その領域が確実に ``malloc`` されるようにします。そのためこれらを使うのは、ユーザが領域を解放することが明確に意図されている
C 文字列に対してのみにすべきです。
.. raw:: html
<a name="string_dup">
.. raw:: html
<a name="cstring_dup">
.. _string_dup:
.. _cstring_dup:
``string_dup s``, ``cstring_dup s``
Convert a pointer ``s`` to a Pure string. Like above, but these functions
take a copy of the string, leaving the original C string untouched.
ポインタ ``s`` を Pure 文字列へ変換します。■上のものと同じように■、これらの関数も文字列のコピーを作り、元々の
C 文字列はそのまま残します。
The reverse transformations are also provided. These take a Pure string to
a byte string (raw ``char*``).
■逆変形■もまた提供されます。これらは Pure 文字列をバイト文字列〔生の
``char*`` 〕へと変えます。
.. raw:: html
<a name="byte_string">
.. raw:: html
<a name="byte_cstring">
.. _byte_string:
.. _byte_cstring:
``byte_string s``, ``byte_cstring s``
Construct a byte string from a Pure string ``s``. The result is a raw
pointer object pointing to the converted string. The original Pure string
is always copied (and, in the case of ``byte_cstring``, converted to the
system encoding). The resulting byte string is a ``malloc``\ ed pointer
which can be used like a C ``char*``, and has to be freed explicitly by
the caller when no longer needed.
Pure 文字列 ``s`` からバイト文字列を構築します。この結果は、変換された文字列を指示する生のポインタオブジェクト〔a raw
pointer object pointing to the converted string〕となります。元々の
Pure 文字列は常にコピーされ(かつ、 ``byte_cstring``
``malloc`` されたポインタであり、 C の ``char*`` 型のように扱うことができ、必要なくなったときには呼び出し側で明示的に領域を解放しなければなりません。
Finally, it is also possible to convert Pure string lists to byte string
vectors and vice versa. These are useful if you need to pass an
``argv``-like string vector (i.e., a ``char**`` or ``char*[]``) to C
routines. The computed C vectors are ``malloc``\ ed pointers which have an
extra ``NULL`` pointer as the last entry, and should thus be usable for
almost any purpose which requires such a string vector in C. They also take
care of garbage-collecting themselves. The original string data is always
copied. As usual, the ``cstring`` variants do automatic conversions to the
system encoding.
最後に、 Pure 文字列のリストをバイト文字列のベクターに変換することも、その逆もまた可能です。これらは
``argv`` のような文字列ベクター(すなわち ``char**`` や ``char*[]`` )を
C ルーチンに渡したいときに役立ちます。計算された C ベクターは
``malloc`` 済みポインタとなり、終端要素には ``NULL`` ポインタが入ります。このため
C においてこうした文字列ベクターを必要とするほぼあらゆる目的に使うことができるでしょう。また、■これら■はガベージ・コレクションの面倒を自分で見ます。元々の文字列データは常にコピーされます。通常通り、
``cstring`` のほうの関数はシステムエンコーディングへの変換を自動で行います。
.. raw:: html
<a name="byte_string_pointer">
.. raw:: html
<a name="byte_cstring_pointer">
.. _byte_string_pointer:
.. _byte_cstring_pointer:
``byte_string_pointer xs``, ``byte_cstring_pointer xs``
Convert a list of Pure strings to a C ``char**``.
Pure 文字列のリストを C の ``char**`` へと変換します。
.. raw:: html
<a name="string_list">
.. raw:: html
<a name="cstring_list">
.. _string_list:
.. _cstring_list:
``string_list n p``, ``cstring_list n p``
Convert a C ``char**`` to a list of Pure strings.
C の ``char**`` を Pure 文字列のリストへと変換します。
Note that the back conversions take an additional first argument which
denotes the number of strings to retrieve. If you know that the vector is
``NULL``-terminated then this can also be an infinite value (``inf``) in
which case the number of elements will be figured out automatically.
Processing always stops at the first ``NULL`` pointer encountered.
逆変換〔back conversions〕が追加の第一引数を取り、この引数は取り戻すべき文字列の数を示していることを忘れないでください。ベクターの終端が ``NULL``
があることがわかっているならば、■第一引数■は無限大値( ``inf`` )でもよく、この場合、要素の数は自動で計算されます。処理は常に、初めて ``NULL`` ポインタと出会ったところで終わります。
Matrix Functions
.. raw:: html
<a name="matrix size">
.. raw:: html
<a name="matrix dimensions">
.. raw:: html
<a name="# (matrix)">
.. raw:: html
<a name="dim">
.. _matrix size:
.. _matrix dimensions:
.. _# (matrix):
.. _dim:
The size of a matrix (number of elements) can be obtained using ``#``, and
the ``dim`` function can be used to return its dimensions (number of rows
and columns):
マトリクスのサイズ(要素数)は ``#`` を使うことで取得できます。また ``dim`` 関数を使うとマトリクスの次元(行と列の数)が返ります::
> let x = {1,2,3;4,5,6}; #x;
> dim x;
.. raw:: html
<a name="null (matrix)">
.. _null (matrix):
``null x`` can be used to check for empty matrices. Note that there are
various kinds of these, as a matrix may have zero rows or columns, or both.
``null x`` を使うとマトリクスが空かどうかチェックできます。空のマトリクスには様々な種類があることを忘れないでください。マトリクスは行と列の数のいずれかがゼロである可能性がありますし、両方ともゼロであるかもしれません。
.. raw:: html
<a name="! (matrix)">
.. _! (matrix):
Indexing and slicing works pretty much like in MATLAB and Octave, except
that the Pure operators ``!`` and ``!!`` are used (and indices are
zero-based). It is possible to access elements with a one-dimensional index
(in row-major oder):
インデックス参照とスライスは MATLAB や Octave
のそれとよく似た動作をします。ただし Pure では演算子 ``!`` と ``!!``
1 つを使って要素にアクセスすることができます(行優先)::
> x!3;
Or you can specify a pair of row and column index:
> x!(1,0);
.. raw:: html
<a name="!! (matrix)">
.. _!! (matrix):
Slicing works accordingly. You can either specify a list of (one- or
two-dimensional) indices, in which case the result is always a row vector:
> x!!(2..5);
Or you can specify a pair of row and column index lists:
> x!!(0..1,1..2);
The following abbreviations are provided to grab a slice from a row or
> x!!(1,1..2);
> x!!(0..1,1);
Matrices can be compared with the ``==`` and ``~=`` operators which check
the dimensions and the matrix elements for equality:
マトリクスは演算子 ``==`` と ``~=`` を使って比較することができます。これらはマトリクスの次元と要素が等値であるかどうかチェックするものです::
> x == transpose x;
Most of the generic list operations are implemented on matrices, see
`Common List Functions`_. Hence operations like ``map`` and ``zipwith``
work as expected:
`Common List Functions`_ を参照して下さい。したがって ``map`` や ``zipwith``
> map succ {1,2,3;4,5,6};
> zipwith (+) {1,2,3;4,5,6} {1,0,1;0,2,0};
The matrix module also provides a bunch of other specialized matrix
operations, including all the necessary operations for matrix
comprehensions. We briefly summarize the most important operations below;
please refer to matrices.pure for all the gory details. Also make sure you
check `Matrix Computations`_ in the Pure Manual for some more examples, and
the `Record Functions`_ section for an implementation of records using
symbolic vectors.
gory な詳細すべてに関してはどうか matrices.pure を参照して下さい。また
Pure Manual 内の `Matrix Computations`_ 〔マトリクス計算〕にももう少し具体例があり、 `Record Functions`_ セクションには記号ベクターを使ったレコードの実装があります。
.. _Matrix Computations: pure.html#matrix-computations
Matrix Construction and Conversions
.. raw:: html
<a name="matrix">
.. _matrix:
.. |matrix| replace:: ``matrix``
The ``matrix`` function converts a list or tuple to a corresponding matrix.
``matrix`` also turns a list of lists or matrices specifying the rows of
the matrix to the corresponding rectangular matrix; otherwise, the result
is a row vector. (In the former case, the ``matrix`` function may throw a
``bad_matrix_value x`` exception in case of dimension mismatch, where ``x``
denotes the offending submatrix.) :
``matrix`` 関数はリストやタプルを、それぞれに相当するマトリクスへ変換します。
``matrix`` はまた、各行を定義した複数のリストかマトリクスを〔各要素として〕持つ1つのリスト〔=複数のリストを含むリスト or 複数のマトリクスを含むリスト〕を、それに相応する正方マトリクスへと変換します。場合によって、結果は1つの行ベクターにもなります(前者のケースでは、マトリクスの次元が一致しない場合に
``matrix`` 関数が ``bad_matrix_value x`` 例外を投げる可能性があります。このとき
``x`` ははみ出た部分のサブマトリクス〔the offending submatrix〕を示します::
> matrix [1,2,3];
> matrix [[1,2,3],[4,5,6]];
.. raw:: html
<a name="rowvector">
.. raw:: html
<a name="colvector">
.. _rowvector:
.. _colvector:
The ``rowvector`` and ``colvector`` functions work in a similar fashion,
but expect a list, tuple or matrix of elements and always return a row or
column vector, respectively (i.e., a 1xn or nx1 matrix, where n is the size
of the converted aggregate). Also, the ``vector`` function is a synonym for
``rowvector``. These functions can also be used to create recursive
(symbolic) matrix structures of arbitrary depth, which provide a nested
array data structure with efficient (constant time) element access. ::
``rowvector`` と ``colvector`` 関数はどちらも同じような動作をしますが、単一のリスト、タプル、マトリクスを引数に取るところは同じでも、それぞれ単一の行を返すか、列を返すかという点が異なります(すなわち、
1xn または nx1 のマトリクスが返ります。このとき n は変換されたまとまり〔the
converted aggregate〕のサイズです)。また、 ``vector`` 関数は ``rowvector``
関数の同義語です。これらの関数を使って、任意の深さを持つ再帰的な(記号)マトリクス構造を作ることができます。これにより、効率的に(定数時間で)要素アクセスを行える入れ子の配列データ構造〔a nested array data structure〕が提供されます。 ::
> rowvector [1,2,3];
> colvector [1,2,3];
> vector [rowvector [1,2,3],colvector [4,5,6]];
.. raw:: html
<a name="dmatrix">
.. raw:: html
<a name="cmatrix">
.. raw:: html
<a name="imatrix">
.. raw:: html
<a name="smatrix">
.. _dmatrix:
.. _cmatrix:
.. _imatrix:
.. _smatrix:
The ``dmatrix``, ``cmatrix``, ``imatrix`` and ``smatrix`` functions convert
a list or matrix to a matrix of the corresponding type (integer, double,
complex or symbolic). If the input is a list, the result is always a row
vector; this is usually faster than the ``matrix`` and ``rowvector``
operations, but requires that the elements already are of the appropriate
type. ::
``dmatrix`` 、 ``cmatrix`` 、 ``imatrix`` および ``smatrix`` 関数は、リストまたはマトリクスを、相応する型(整数、浮動小数点数、虚数、記号)のマトリクスに変換します。入力がリストである場合、結果は常に行ベクターとなります。通常、これらの関数は
``matrix`` や ``rowvector`` よりも高速に処理を行いますが、中の要素がすでに適切な型へ変換されている必要があります。 ::
> imatrix [1,2,3];
> dmatrix {1,2,3;4,5,6};
The ``dmatrix``, ``cmatrix`` and ``imatrix`` functions can also be invoked
with either an int ``n`` or a pair ``(n,m)`` of ints as argument, in which
case they construct a zero rowvector or matrix with the corresponding
dimensions. ::
``dmatrix`` 、 ``cmatrix`` および ``imatrix`` 関数は、単一の整数 ``n``
または整数のペア ``(n,m)`` を引数として呼び出すことができます。この場合、すべての要素をゼロとする行ベクターか、指定された次元を持つマトリクスが構築されます。 ::
> imatrix 3;
> imatrix (2,3);
There's also a number of more specialized conversions operations which are
discussed under `Matrix Inspection and Manipulation`_ below.
`Matrix Inspection and Manipulation`_ で議論されています。
.. raw:: html
<a name="list (matrix)">
.. raw:: html
<a name="list2 (matrix)">
.. raw:: html
<a name="tuple (matrix)">
.. _list (matrix):
.. _list2 (matrix):
.. _tuple (matrix):
Conversely, a matrix can be converted back to a flat list or tuple with the
``list`` and ``tuple`` functions. In addition, the ``list2`` function
converts a matrix to a list of lists (one sublist for each row of the
matrix). ::
逆に、 ``list`` や ``tuple`` 関数を使い、マトリクスを変換してフラットなリストやタプルへ戻すことも可能です。さらに ``list2``
関数は1つのマトリクスを、複数のリストを要素とするの1つリスト(マトリクスの1行が1つのサブリストとなる)へと変換します。 ::
> tuple {1,2,3;4,5,6};
> list {1,2,3;4,5,6};
> list2 {1,2,3;4,5,6};
> list2 {1,2,3};
Matrix Inspection and Manipulation
.. raw:: html
<a name="dmatrixp">
.. raw:: html
<a name="cmatrixp">
.. raw:: html
<a name="imatrixp">
.. raw:: html
<a name="smatrixp">
.. raw:: html
<a name="nmatrixp">
.. _dmatrixp:
.. _cmatrixp:
.. _imatrixp:
.. _smatrixp:
.. _nmatrixp:
``dmatrixp x``, ``cmatrixp x``, ``imatrixp x``, ``smatrixp x``, ``nmatrixp x``
Check for different kinds of matrices (double, complex, int, symbolic and
numeric, i.e., non-symbolic).
.. raw:: html
<a name="vectorp">
.. raw:: html
<a name="rowvectorp">
.. raw:: html
<a name="colvectorp">
.. _vectorp:
.. _rowvectorp:
.. _colvectorp:
``vectorp x``, ``rowvectorp x``, ``colvectorp x``
Check for different kinds of vectors (these are just matrices with one
row or column).
.. raw:: html
<a name="stride">
.. _stride:
``stride x``
The stride of a matrix denotes the real row size of the underlying C
array, see the description of the |pack|_ function below for further
details. There's little use for this value in Pure, but it may be needed
when interfacing to C.
.. raw:: html
<a name="row">
.. raw:: html
<a name="col">
.. _row:
.. _col:
``row x i``, ``col x i``
Extract the ``i``\ th row or column of a matrix.
.. raw:: html
<a name="rows">
.. raw:: html
<a name="cols">
.. _rows:
.. _cols:
``rows x``, ``cols x``
Return the list of all rows or columns of a matrix.
.. raw:: html
<a name="diag">
.. raw:: html
<a name="subdiag">
.. raw:: html
<a name="supdiag">
.. _diag:
.. _subdiag:
.. _supdiag:
``diag x``, ``subdiag x k``, ``supdiag x k``:
Extract (sub-,super-) diagonals from a matrix. Sub- and super-diagonals
for ``k=0`` return the main diagonal. Indices for sub- and
super-diagonals can also be negative, in which case the corresponding
super- or sub-diagonal is returned instead. In each case the result is a
row vector.
.. raw:: html
<a name="submat">
.. _submat:
``submat x (i,j) (n,m)``
Extract a submatrix of a given size at a given offset. The result shares
the underlying storage with the input matrix (i.e., matrix elements are
*not* copied) and so this is a comparatively cheap operation.
.. raw:: html
<a name="rowcat">
.. raw:: html
<a name="colcat">
.. _rowcat:
.. _colcat:
``rowcat xs``, ``colcat xs``
Construct matrices from lists of rows and columns. These take either
scalars or submatrices as inputs; corresponding dimensions must match.
``rowcat`` combines submatrices vertically, like ``{x;y}``; ``colcat``
combines them horizontally, like ``{x,y}``. Note: Like the built-in
matrix constructs, these operations may throw a ``bad_matrix_value x``
exception in case of dimension mismatch, where ``x`` denotes the
offending submatrix.
.. raw:: html
<a name="matcat">
.. _matcat:
``matcat xs``
Construct a matrix from a (symbolic) matrix of other matrices and/or
scalars. This works like a combination of ``rowcat`` and ``colcat``, but
draws its input from a matrix instead of a list of matrices, and
preserves the overall layout of the "host" matrix. The net effect is that
the host matrix is flattened out. If all elements of the input matrix are
scalars already, the input matrix is returned unchanged.
.. raw:: html
<a name="rowcatmap">
.. raw:: html
<a name="colcatmap">
.. _rowcatmap:
.. _colcatmap:
.. |rowcat| replace:: ``rowcat``
.. |colcat| replace:: ``colcat``
``rowcatmap f xs``, ``colcatmap f xs``
Combinations of |rowcat|_, |colcat|_ and |map|_. These are used, in
particular, for implementing matrix comprehensions.
.. raw:: html
<a name="diagmat">
.. raw:: html
<a name="subdiagmat">
.. raw:: html
<a name="supdiagmat">
.. _diagmat:
.. _subdiagmat:
.. _supdiagmat:
``diagmat x``, ``subdiagmat x k``, ``supdiagmat x k``
Create a (sub-,super-) diagonal matrix from a row vector ``x`` of size
``n``. The result is always a square matrix with dimension ``(n+k,n+k)``,
which is of the same matrix type (double, complex, int, symbolic) as the
input and has the elements of the vector on its ``k``\ th sub- or
super-diagonal, with all other elements zero. A negative value for ``k``
turns a sub- into a super-diagonal matrix and vice versa.
.. raw:: html
<a name="re (matrix)">
.. raw:: html
<a name="im (matrix)">
.. raw:: html
<a name="conj (matrix)">
.. _re (matrix):
.. _im (matrix):
.. _conj (matrix):
``re x``, ``im x``, ``conj x``
Extract the real and imaginary parts and compute the conjugate of a
numeric matrix.
.. raw:: html
<a name="pack">
.. raw:: html
<a name="packed">
.. _pack:
.. _packed:
.. |pack| replace:: ``pack``
.. |packed| replace:: ``packed``
.. |submat| replace:: ``submat``
``pack x``, ``packed x``
Pack a matrix. This creates a copy of the matrix which has the data in
contiguous storage. It also frees up extra memory if the matrix was
created as a slice from a bigger matrix (see |submat|_ above) which has
since gone the way of the dodo. The ``packed`` predicate can be used to
verify whether a matrix is already packed. Note that even if a matrix is
already packed, ``pack`` will make a copy of it anyway, so ``pack`` also
provides a quick way to copy a matrix, e.g., if you want to pass it as an
input/output parameter to a GSL routine.
.. raw:: html
<a name="redim">
.. _redim:
``redim (n,m) x``, ``redim n x``
Change the dimensions of a matrix without changing its size. The total
number of elements must match that of the input matrix. Reuses the
underlying storage of the input matrix if possible (i.e., if the matrix
is |packed|_). You can also redim a matrix to a given row size ``n``. In
this case the row size must divide the total size of the matrix.
.. raw:: html
<a name="sort (matrix)">
.. _sort (matrix):
``sort p x``
Sorts the elements of a matrix (non-destructively, i.e., without changing
the original matrix) according to the given predicate, using the C
``qsort`` function. This works exactly the same as with lists (see
`Common List Functions`_), except that it takes and returns a matrix
instead of a list. Note that the function sorts *all* elements of the
matrix in one go (regardless of the dimensions), as if the matrix was a
single big vector. The result matrix has the same dimensions as the input
matrix. Example::
> sort (<) {10,9;8,7;6,5};
If you'd like to sort the individual rows instead, you can do that as
> sort_rows p = rowcat . map (sort p) . rows;
> sort_rows (<) {10,9;8,7;6,5};
Likewise, to sort the columns of a matrix::
> sort_cols p = colcat . map (sort p) . cols;
> sort_cols (<) {10,9;8,7;6,5};
Also note that the pure-gsl module provides an interface to the GSL
routines for sorting numeric (int and double) vectors using the standard
order. These will usually be much faster than ``sort``, whereas ``sort``
is more flexible in that it also allows you to sort symbolic matrices and
to choose the order predicate.
.. raw:: html
<a name="transpose (matrix)">
.. _transpose (matrix):
``transpose x``
Transpose a matrix. Example::
> transpose {1,2,3;4,5,6};
.. raw:: html
<a name="rowrev">
.. raw:: html
<a name="colrev">
.. raw:: html
<a name="reverse (matrix)">
.. _rowrev:
.. _colrev:
.. _reverse (matrix):
``rowrev x``, ``colrev x``, ``reverse x``
Reverse a matrix. ``rowrev`` reverses the rows, ``colrev`` the columns,
``reverse`` both dimensions.
Pointers and Matrices
Last but not least, the matrix module also offers a bunch of low-level
operations for converting between matrices and raw pointers. These are
typically used to shovel around massive amounts of numeric data between
Pure and external C routines, when performance and throughput is an
important consideration (e.g., graphics, video and audio applications). The
usual caveats concerning direct pointer manipulations apply.
.. raw:: html
<a name="pointer (matrix)">
.. _pointer (matrix):
``pointer x``
Get a pointer to the underlying C array of a matrix. The data is *not*
copied. Hence you have to be careful when passing such a pointer to C
functions if the underlying data is non-contiguous; when in doubt, first
use the |pack|_ function to place the data in contiguous storage, or use
one of the matrix-pointer conversion routines below.
.. raw:: html
<a name="double_pointer">
.. raw:: html
<a name="float_pointer">
.. raw:: html
<a name="complex_pointer">
.. raw:: html
<a name="complex_float_pointer">
.. raw:: html
<a name="int_pointer">
.. raw:: html
<a name="short_pointer">
.. raw:: html
<a name="byte_pointer">
.. _double_pointer:
.. _float_pointer:
.. _complex_pointer:
.. _complex_float_pointer:
.. _int_pointer:
.. _short_pointer:
.. _byte_pointer:
The following operations copy the contents of a matrix to a given pointer
and return that pointer, converting to the target data type on the fly if
necessary. The given pointer may also be ``NULL``, in which case suitable
memory is malloced and returned; otherwise the caller must ensure that the
memory pointed to by ``p`` is big enough for the contents of the given
* ``double_pointer p x``
* ``float_pointer p x``
* ``complex_pointer p x``
* ``complex_float_pointer p x``
* ``int_pointer p x``
* ``short_pointer p x``
* ``byte_pointer p x``
.. raw:: html
<a name="double_matrix">
.. raw:: html
<a name="float_matrix">
.. raw:: html
<a name="complex_matrix">
.. raw:: html
<a name="complex_float_matrix">
.. raw:: html
<a name="int_matrix">
.. raw:: html
<a name="short_matrix">
.. raw:: html
<a name="byte_matrix">
.. _double_matrix:
.. _float_matrix:
.. _complex_matrix:
.. _complex_float_matrix:
.. _int_matrix:
.. _short_matrix:
.. _byte_matrix:
Conversely, the following functions allow you to create a numeric matrix
from a pointer, copying the data and converting it from the source type on
the fly if necessary. The source pointer ``p`` may also be ``NULL``, in
which case the new matrix is filled with zeros instead. Otherwise the
caller must ensure that the pointer points to properly initialized memory
big enough for the requested dimensions. The given dimension may also be
just an integer ``n`` if a row vector is to be created.
* ``double_matrix (n,m) p``
* ``float_matrix (n,m) p``
* ``complex_matrix (n,m) p``
* ``complex_float_matrix (n,m) p``
* ``int_matrix (n,m) p``
* ``short_matrix (n,m) p``
* ``byte_matrix (n,m) p``
.. raw:: html
<a name="double_matrix_view">
.. raw:: html
<a name="complex_matrix_view">
.. raw:: html
<a name="int_matrix_view">
.. _double_matrix_view:
.. _complex_matrix_view:
.. _int_matrix_view:
Finally, you can use the following operations to create a numeric matrix
view of existing data, without copying the data. The data must be double,
complex or int, the pointer must not be ``NULL`` and the caller must also
ensure that the memory persists for the entire lifetime of the matrix
object. The given dimension may also be just an integer ``n`` if a row
vector view is to be created.
* ``double_matrix_view (n,m) p``
* ``complex_matrix_view (n,m) p``
* ``int_matrix_view (n,m) p``
Record Functions
As of Pure 0.41, the prelude also provides a basic record data structure,
implemented as symbolic vectors of ``key=>value`` pairs which support a few
dictionary-like operations such as ``member``, ``insert`` and indexing.
Records may be represented as row, column or empty vectors (i.e., the
number of rows or columns must be zero or one). They must be symbolic
matrices consisting only of "hash pairs" ``key=>value``, where the keys can
be either symbols or strings. The values can be any kind of Pure data; in
particular, they may themselves be records, so records can be nested.
The following operations are provided. Please note that all updates of
record members are non-destructive and thus involve copying, which might be
slow for large record values; if this is a problem then you should use
dictionaries instead (cf. Dictionaries_). Or you can create mutable records
by using expression references (cf. `Expression References`_) as values,
which allow you to modify the data in-place.
Also note that records with duplicate keys are permitted; in such a case
the following operations will always operate on the *last* entry for a
given key.
.. recordp:
``recordp x``
Check for record values.
.. raw:: html
<a name="record">
.. _record:
``record x``
Normalizes a record. This removes duplicate keys and orders the record by
keys (using an apparently random but well-defined order of the key
values), so that normalized records are syntactically equal (``===``) if
and only if they contain the same hash pairs. For convenience, this
function can also be used directly on lists and tuples of hash pairs to
convert them to a normalized record value.
.. raw:: html
<a name="# (record)">
.. _# (record):
The size of a record (number of entries it contains). Duplicate entries
are counted. (This is in fact just the standard matrix size operation.)
.. raw:: html
<a name="member (record)">
.. _member (record):
``member x y``
Check whether ``x`` contains the key ``y``.
.. raw:: html
<a name="! (record)">
.. _! (record):
Retrieves the (last) value associated with the key ``y`` in ``x``, if
any, otherwise throws an ``out_of_bound`` exception.
.. raw:: html
<a name="!! (record)">
.. _!! (record):
Slicing also works as expected, by virtue of the generic definition of
slicing provided by the matrix data structure.
.. raw:: html
<a name="insert (record)">
.. raw:: html
<a name="update (record)">
.. _insert (record):
.. _update (record):
``insert x (y=>z)``, ``update x y z``
Associate the key ``y`` with the value ``z`` in ``x``. If ``x`` already
contains the key ``y`` then the corresponding value is updated (the last
such value if ``x`` contains more than one association for ``y``),
otherwise a new member is inserted at the end of the record.
.. raw:: html
<a name="delete (record)">
.. _delete (record):
``delete x y``
Delete the key ``y`` (and its associated value) from ``x``. If ``x``
contains more than one entry for ``y`` then the last such entry is
.. raw:: html
<a name="keys (record)">
.. raw:: html
<a name="vals (record)">
.. _keys (record):
.. _vals (record):
``keys x``, ``vals x``
List the keys and associated values of ``x``. If the record contains
duplicate keys, they are all listed in the order in which they are stored
in the record.
Here are a few basic examples::
> let r = {x=>5, y=>12};
> r!y; r!![y,x]; // indexing and slicing
> keys r; vals r; // keys and values of a record
> insert r (x=>99); // update an existing entry
> insert ans (z=>77); // add a new entry
> delete ans z; // delete an existing entry
> let r = {r,x=>7,z=>3}; r; // duplicate key x
> r!x, r!z; // indexing returns the last value of x
> delete r x; // delete removes the last entry for x
> record r; // normalize (remove dups and sort)
> record [x=>5, x=>7, y=>12]; // construct a normalized record from a list
> record (x=>5, x=>7, y=>12); // ... or a tuple
.. _Record Data: pure.html#record-data
More examples can be found in the `Record Data`_ section in the Pure
This prelude module is a collection of various lowlevel operations, which
are implemented either directly by machine instructions or by C functions
provided in the runtime. In particular, this module defines the basic
arithmetic and logic operations on machine integers, bigints and floating
point numbers, as well as various type checking predicates and conversions
between different types. Some low-level pointer operations are also
provided, as well as "sentries" (Pure's flavour of object finalizers) and
"references" (mutable expression pointers).
The basic arithmetic and logic operations provided by this module are
summarized in the following table:
.. raw:: html
<a name="+">
.. raw:: html
<a name="-">
.. raw:: html
<a name="*">
.. raw:: html
<a name="/">
.. raw:: html
<a name="div">
.. raw:: html
<a name="mod">
.. raw:: html
<a name="^">
.. raw:: html
<a name="==">
.. raw:: html
<a name="~=">
.. raw:: html
<a name="<">
.. raw:: html
<a name=">">
.. raw:: html
<a name="<=">
.. raw:: html
<a name=">=">
.. raw:: html
<a name="~">
.. raw:: html
<a name="&&">
.. raw:: html
<a name="||">
.. raw:: html
<a name="not">
.. raw:: html
<a name="and">
.. raw:: html
<a name="or">
.. raw:: html
<a name="<<">
.. raw:: html
<a name=">>">
.. _+:
.. _-:
.. _*:
.. _/:
.. _div:
.. _mod:
.. _^:
.. _==:
.. _~=:
.. _<:
.. _>:
.. _<=:
.. _>=:
.. _~:
.. _&&:
.. _||:
.. _not:
.. _and:
.. _or:
.. _<<:
.. _>>:
=========== =============== =========================================
Kind Operator Meaning
=========== =============== =========================================
Arithmetic ``+`` ``-`` addition, subtraction (also unary minus),
``*`` ``/`` multiplication, division (inexact),
``div`` ``mod`` exact int/bigint division/modulus,
``^`` exponentiation (inexact)
Comparisons ``==`` ``~=`` equality, inequality,
``<`` ``>`` less than, greater than,
``<=`` ``>=`` less than or equal, greater than or equal
Logic ``~`` logical not,
``&&`` ``||`` and, or (short-circuit)
Bitwise ``not`` bitwise not,
``and`` ``or`` and, or,
``<<`` ``>>`` bit shifts
=========== =============== =========================================
Precedence and and associativity of the operators can be found in the
operators_ table at the beginning of this section.
The names of some operations are at odds with C. Note, in particular, that
logical negation is denoted ``~`` instead of ``!`` (and, consequently,
``~=`` denotes inequality, rather than ``!=``), and the bitwise operations
are named differently. This is necessary because Pure uses ``!``, ``&`` and
``|`` for other purposes. Also, ``/`` always denotes inexact (double)
division in Pure, whereas the integer division operators are called ``div``
and ``mod``. (``%``, which is not defined by this module, also has a
different meaning in Pure; it's the exact division operator, see `Rational
The above operations are implemented for int, bigint and, where
appropriate, double and pointer operands. (Pointer arithmetic comprises
``+`` and ``-`` and works in the usual way, i.e., ``p-q`` returns the byte
offset between two pointers ``p`` and ``q``, and ``p+n`` or ``p-n`` offsets
a pointer ``p`` by the given integer ``n`` denoting the amount of bytes.)
The math module (see `Mathematical Functions`_) also provides
implementations of the arithmetic and comparison operators for rational,
complex and complex rational numbers.
Note that the logical operations are actually implemented as special forms
in order to provide for short-circuit evaluation. This needs special
support from the compiler to work. The primitives module still provides
definitions for these, as well as other special forms like ``quote`` and
the thunking operator ``&`` so that they may be used as function values and
in partial applications, but when used in this manner they lose all their
special call-by-name properties; see `Special Forms`_ in the Pure Manual
for details.
The constants ``inf`` and ``nan`` are defined as the usual IEEE floating
point infinities and NaNs, and the predicates ``infp`` and ``nanp`` are
provided to check for these kinds of values.
In addition, the following arithmetic and numeric functions are provided:
.. raw:: html
<a name="abs">
.. raw:: html
<a name="sgn">
.. _abs:
.. _sgn:
``abs x``, ``sgn x``
Absolute value and sign of a number.
.. raw:: html
<a name="min">
.. raw:: html
<a name="max">
.. _min:
.. _max:
``min x y``, ``max x y``
Minimum and maximum of two values. This works with any kind of values
which have the ordering relations defined on them.
.. raw:: html
<a name="succ">
.. raw:: html
<a name="pred">
.. _succ:
.. _pred:
``succ x``, ``pred x``
Successor (``+1``) and predecessor (``-1``) functions.
.. raw:: html
<a name="gcd">
.. raw:: html
<a name="lcd">
.. _gcd:
.. _lcd:
``gcd x y``, ``lcd x y``
The greatest common divisor and least common multiple functions from the
GMP library. These return a bigint if at least one of the arguments is a
bigint, a machine int otherwise.
.. raw:: html
<a name="pow">
.. _pow:
``pow x y``
Computes exact powers of ints and bigints. The result is always a
bigint. Note that ``y`` must always be nonnegative here, but see the math
module (`Mathematical Functions`_) which deals with the case ``y<0``
using rational numbers.
These operations convert between various types of Pure values.
.. raw:: html
<a name="hash">
.. _hash:
``hash x``
Compute a 32 bit hash code of a Pure expression.
.. raw:: html
<a name="int">
.. raw:: html
<a name="bigint">
.. raw:: html
<a name="double">
.. raw:: html
<a name="pointer">
.. _int:
.. _bigint:
.. _double:
.. _pointer:
``int x``, ``bigint x``, ``double x``, ``pointer x``
Conversions between the different numeric and pointer types.
.. raw:: html
<a name="ubyte">
.. raw:: html
<a name="ushort">
.. raw:: html
<a name="uint">
.. raw:: html
<a name="uint64">
.. raw:: html
<a name="ulong">
.. _ubyte:
.. _ushort:
.. _uint:
.. _uint64:
.. _ulong:
``ubyte x``, ``ushort x``, ``uint x``, ``uint64 x``, ``ulong x``
Convert signed (8/16/32/64) bit integers to the corresponding unsigned
quantities. These functions behave as if the value was "cast" to the
corresponding unsigned C type, and are most useful for dealing with
unsigned integers returned by external C routines. The routines always
use the smallest Pure int type capable of holding the result: ``int`` for
``ubyte`` and ``ushort``, ``bigint`` for ``uint``, ``uint64`` and
``ulong``. All routines take int parameters. In the case of ``uint64``, a
bigint parameter is also permitted (which is what the C interface returns
for 64 bit values). Also note that ``ulong`` reduces to either ``uint``
or ``uint64``, depending on the size of ``long`` for the host
The following _`rounding functions` work with all kinds of numbers:
.. raw:: html
<a name="floor">
.. raw:: html
<a name="ceil">
.. _floor:
.. _ceil:
``floor x``, ``ceil x``
Floor and ceil.
.. raw:: html
<a name="round">
.. raw:: html
<a name="trunc">
.. _round:
.. _trunc:
``round x``, ``trunc x``
Round or truncate to an integer.
.. raw:: html
<a name="frac">
.. _frac:
``frac x``
Fractional part (``x-trunc x``).
Note that all these functions return double values for double arguments, so
if you need an integer result then you'll have to apply a suitable
conversion, as in ``int (floor x)``.
A syntactic equality test is provided, as well as various type checking
.. raw:: html
<a name="same">
.. raw:: html
<a name="===">
.. raw:: html
<a name="~==">
.. _same:
.. _===:
.. _~==:
``x===y``, ``x~==y``, ``same x y``
Syntactic equality. In difference to ``==`` and ``~=`` this is defined on
all Pure expressions. Basically, two expressions are syntactically equal
if they print out the same in the interpreter. In the special case of
pointer objects and closures, which do not have a syntactic
representation in Pure, ``x`` and ``y`` must be the same object (same
pointer value or function).
.. raw:: html
<a name="intp">
.. raw:: html
<a name="bigintp">
.. raw:: html
<a name="doublep">
.. raw:: html
<a name="stringp">
.. raw:: html
<a name="pointerp">
.. raw:: html
<a name="matrixp">
.. _intp:
.. _bigintp:
.. _doublep:
.. _stringp:
.. _pointerp:
.. _matrixp:
``intp x``, ``bigintp x``, ``doublep x``, ``stringp x``, ``pointerp x``, ``matrixp x``
Predicates to check for the built-in types.
.. raw:: html
<a name="charp">
.. _charp:
``charp x``
Single character string predicate.
.. raw:: html
<a name="numberp">
.. raw:: html
<a name="complexp">
.. raw:: html
<a name="realp">
.. raw:: html
<a name="rationalp">
.. raw:: html
<a name="integerp">
.. _numberp:
.. _complexp:
.. _realp:
.. _rationalp:
.. _integerp:
``numberp x``, ``complexp x``, ``realp x``, ``rationalp x``, ``integerp x``
Additional number predicates.
.. raw:: html
<a name="exactp">
.. raw:: html
<a name="inexactp">
.. _exactp:
.. _inexactp:
``exactp x``, ``inexactp x``
Check whether a number is exact (i.e., doesn't contain any double
.. raw:: html
<a name="applp">
.. raw:: html
<a name="listp">
.. raw:: html
<a name="listnp">
.. raw:: html
<a name="tuplep">
.. _applp:
.. _listp:
.. _listnp:
.. _tuplep:
``applp x``, ``listp x``, ``listnp x``, ``tuplep x``
Predicates to check for function applications, proper lists, list nodes
and proper tuples.
.. raw:: html
<a name="funp">
.. raw:: html
<a name="lambdap">
.. raw:: html
<a name="thunkp">
.. raw:: html
<a name="varp">
.. _funp:
.. _lambdap:
.. _thunkp:
.. _varp:
``funp x``, ``lambdap x``, ``thunkp x``, ``varp x``
Predicates to check for various kinds of function objects (named,
anonymous or thunk), and free variable symbols.
.. raw:: html
<a name="atomp">
.. raw:: html
<a name="closurep">
.. _atomp:
.. _closurep:
``atomp x``, ``closurep x``
Convenience functions to check for atoms (named function or variable) and
closures (named function or lambda).
The following operations let you peek at various internal information that
the interpreter provides to Pure programs either for convenience or for
metaprogramming purposes. They are complemented by the evaluation
primitives discussed below, see `Eval and Friends`_.
.. raw:: html
<a name="ans">
.. _ans:
Retrieve the most recently printed result of a toplevel expression
evaluated in the read-eval-print loop. This is just a convenience for
interactive usage. Note that the ``ans`` value will stick around until a
new expression is computed. (It is possible to clear the ``ans`` value
with the interactive command ``clear ans``, however.) Example::
> 1/3;
> ans/2;
.. raw:: html
<a name="\__locals__">
.. _\__locals__:
Return a list with the local function bindings (``with`` clauses) visible
at this point in the program. This is actually implemented as a
built-in. The return value is a list of "hash" pairs ``x=>f`` where ``x``
is the (quoted) symbol denoting the function and ``f`` is the function
itself (or its value, if ``f`` is a parameterless function). The
``__locals__`` function is useful for debugging purposes, as well as to
implement dynamic environments. It is also used internally to implement
the |reduce|_ macro, see `Eval and Friends`_. Example::
> __locals__ with foo x = x+1; x = a+b end;
> f 99 when _=>f = ans!1 end;
.. |reduce| replace:: ``reduce``
The prelude also provides some functions to retrieve various attributes of
a function symbol which determine how the operation is applied to its
operands or arguments. These functions all take a single argument, the
symbol or function object to be inspected, and return an integer value.
.. raw:: html
<a name="nargs">
.. _nargs:
``nargs x``
Get the argument count of a function object, i.e., the number of
arguments it expects. Returns 0 for thunks and saturated applications, -1
for over-saturated applications and non-functions.
.. raw:: html
<a name="arity">
.. _arity:
``arity x``
Determine the arity of an operator symbol. The returned value is 0, 1 or
2 for nullary, unary and binary symbols, respectively, -1 for symbols
without a fixity declaration or other kinds of objects.
.. raw:: html
<a name="fixity">
.. _fixity:
``fixity f``
Determine the fixity of an operator symbol. The fixity is encoded as an
integer ``10*n+m`` where ``n`` is the precedence level (ranging
from ``0`` to ``PREC_MAX``, where ``PREC_MAX`` denotes the precedence of
primary expressions, 16777216 in the current implementation) and ``m``
indicates the actual fixity at each level, in the order of increasing
precedence (0 = infix, 1 = infixl, 2 = infixr, 3 = prefix, 4 =
postfix). The fixity value of nonfix and outfix symbols, as well as
symbols without a fixity declaration, is always given as ``10*PREC_MAX``,
and the same value is also reported for non-symbol objects. Infix, prefix
and postfix symbols always have a ``fixity`` value less than
``10*PREC_MAX``. (``PREC_MAX`` isn't actually defined as a constant
anywhere, but you can easily do that yourself by setting ``PREC_MAX`` to
the fixity value of any nonfix symbol or non-symbol value, e.g.: ``const
PREC_MAX = fixity [];``)
Note that only closures (i.e., named and anonymous functions and thunks)
have a defined argument count in Pure, otherwise ``nargs`` returns -1
indicating an unknown argument count. Partial applications of closures
return the number of remaining arguments, which may be zero to indicate a
`saturated` (but unevaluated) application, or -1 for `over-saturated` and
constructor applications. (Note that in Pure a saturated application may
also remain unevaluated because there is no definition for the given
combination of arguments and thus the expression is in normal form, or
because the application was quoted. If such a normal form application is
then applied to some "extra" arguments it becomes over-saturated.)
The value returned by ``nargs`` always denotes the actual argument count of
the given function, regardless of the declared arity if the function also
happens to be an operator symbol. Often these will coincide (as, e.g., in
the case of ``+`` which is a binary operator and also expects two
arguments). But this is not necessarily the case, as shown in the following
example of a binary operator which actually takes *three* arguments::
> infix 0 oops;
> (oops) x y z = x*z+y;
> arity (oops);
> nargs (oops);
> nargs (5 oops 8);
> map (5 oops 8) (1..5);
Eval and Friends
Pure provides some rather powerful operations to convert between Pure
expressions and their string representation, and to evaluate quoted
expressions (``'x``). The string conversions ``str``, ``val`` and ``eval``
also provide a convenient means to serialize Pure expressions, e.g., when
terms are to be transferred to/from persistent storage. (Note, however,
that this has its limitations. Specifically, some objects like pointers and
anonymous functions do not have a parsable string representation. Also see
the `Expression Serialization`_ section for some dedicated serialization
operations which provide a more compact binary serialization format.)
.. raw:: html
<a name="str">
.. _str:
``str x``
Yields the print representation of an expression in Pure syntax, as a
.. raw:: html
<a name="val (string)">
.. _val (string):
``val s``
Parses a single simple expression, specified as a string in Pure syntax,
and returns the result as is, without evaluating it. Note that this is
much more limited than the ``eval`` operation below, as the expression
must not contain any of the special constructs (conditional expressions,
``when``, ``with``, etc.).
.. raw:: html
<a name="eval">
.. _eval:
``eval x``
Parses any expression, specified as a string in Pure syntax, and returns
its value. In fact, ``eval`` can also parse and execute arbitrary Pure
code. In that case it will return the last computed expression, if any.
Alternatively, ``eval`` can also be invoked on a (quoted) Pure
expression, which is recompiled and then evaluated. Exceptions during
evaluation are reported back to the caller.
.. raw:: html
<a name="evalcmd">
.. _evalcmd:
``evalcmd x``
Like ``eval``, but allows execution of interactive commands and returns
their captured output as a string. No other results are returned, so this
operation is most useful for executing Pure definitions and interactive
commands for their side-effects. (At this time, only the regular output
of a few commands can be captured, most notably ``bt``, ``clear``,
``mem``, ``save`` and ``show``; otherwise the result string will be
.. raw:: html
<a name="lasterr">
.. _lasterr:
Reports errors in ``eval`` and ``evalcmd``. This string value will be
nonempty iff a compilation or execution error was encountered during the
most recent invokation of ``eval`` and ``evalcmd``. In that case each
reported error message is terminated with a newline character.
.. raw:: html
<a name="reduce">
.. _reduce:
``reduce x``
Reevaluates an expression in a local environment. This dynamically
rebinds function symbols in the given expression to whatever local
definitions are in effect at the point of the ``reduce`` call. Note that
``reduce`` is actually implemented as a macro which expands to the
``reduce_with`` primitive (see below), using the |__locals__|_ builtin to
enumerate the bindings which are in effect at the call site.
.. raw:: html
<a name="reduce_with">
.. _reduce_with:
``reduce_with env x``
Like ``reduce`` above, but takes a list of replacements (given as hash
pairs ``u=>v``) as the first argument. The ``reduce`` macro expands to
``reduce_with __locals__``.
.. |__locals__| replace:: ``__locals__``
> str (1/3);
> val "1/3";
> eval "1/3";
> eval ('(1/3));
> evalcmd "show evalcmd";
"extern expr* evalcmd(expr*);\n"
> eval "1/3)";
eval "1/3)"
> lasterr;
"<stdin>, line 1: syntax error, unexpected ')', expecting '=' or '|'\n"
The ``reduce`` macro provides a restricted form of dynamic binding which is
useful to implement local rewriting rules. It is invoked without parameters
and expands to the curried call ``reduce_with __locals__`` of the
``reduce_with`` primitive, which takes one additional argument, the
expression to be rewritten. The following example shows how to expand or
factorize an expression using local rules for the corresponding laws of
expand = reduce with
(a+b)*c = a*c+b*c;
a*(b+c) = a*b+a*c;
factor = reduce with
a*c+b*c = (a+b)*c;
a*b+a*c = a*(b+c);
expand ((a+b)*2); // yields a*2+b*2
factor (a*2+b*2); // yields (a+b)*2
Note that instances of locally bound functions are substituted back in the
computed result, thus the instances of ``*`` and ``+`` in the results
``a*2+b*2`` and ``(a+b)*2`` shown above denote the corresponding globals,
not the local incarnations of ``*`` and ``+`` defined in ``expand`` and
``factor``, respectively.
``reduce`` also adjusts to quoted arguments. In this case, the local rules
are applied as usual, but back-substituted globals are *not* evaluated in
the result::
> expand ((a+1)*2);
> expand ('((a+1)*2));
Note that ``reduce`` only takes into account local *function* bindings from
``with`` clauses, local *variable* bindings do not affect its operation in
any way::
> let y = [x,x^2,x^3];
> reduce y when x = u+v end;
However, in such cases you can perform the desired substitution by turning
the ``when`` into a ``with`` clause::
> reduce y with x = u+v end;
Or you can just invoke the underlying ``reduce_with`` builtin directly,
with the desired substitutions given as hash pairs in the first argument::
> reduce_with [x=>u+v] y;
Expression Serialization
Like ``str`` and ``eval``, the following ``blob`` and ``val`` operations
can be used to safely transfer expression data to/from persistent storage
and between different processes (using, e.g., POSIX shared memory, pipes or
sockets). However, ``blob`` and ``val`` use a binary format which is
usually much more compact and gets processed much faster than the string
representations used by ``str`` and ``eval``. Also, ``val`` offers some
additional protection against transmission errors through a crc check. (The
advantage of the string representation, however, is that it's readable
plain text in Pure syntax.)
.. raw:: html
<a name="blob">
.. _blob:
``blob x``
Stores the contents of the given expression as a binary object. The
return value is a cooked pointer which frees itself when
.. raw:: html
<a name="val (blob)">
.. _val (blob):
``val p``
Reconstructs a serialized expression from the result of a previous
invocation of the ``blob`` function.
.. raw:: html
<a name="blobp">
.. _blobp:
``blobp p``
Checks for a valid ``blob`` object. (Note that ``val`` may fail even if
``blobp`` returns ``true``, because for performance reasons ``blobp``
only does a quick plausibility check on the header information of the
blob, whereas ``val`` also performs a crc check and verifies data
.. raw:: html
<a name="blob_size">
.. raw:: html
<a name="blob_crc">
.. _blob_size:
.. _blob_crc:
``blob_size p``, ``blob_crc p``
Determines the size (in bytes) and crc checksum of a blob, respectively.
``blob_size`` always returns a bigint, ``blob_crc`` a machine int (use
``uint`` on the latter to get a proper unsigned 32 bit value). For
convenience, ``#p`` is defined as an alias for ``blob_size p`` on
``blob`` pointers.
> let b = blob {"Hello, world!", 1/3, 4711, NULL};
> b; #b; uint $ blob_crc b;
#<pointer 0x141dca0>
> val b;
{"Hello, world!",0.333333333333333,4711,#<pointer 0>}
Please note that the current implementation has some limitations:
* Just as with ``str`` and ``eval``, runtime data (local closures and
pointers other than the ``NULL`` pointer) can't be serialized, causing
``blob`` to fail. However, it *is* possible to transfer a global
function, provided that the function exists (and is the same) in both the
sending and the receiving process. (This condition can't be verified
by ``val`` and thus is at the programmer's responsibilty.)
* Sharing of subexpressions will in general be preserved, but sharing of
list and tuple *tails* will be lost (unless the entire list or tuple is
* The ``val`` function may fail to reconstruct the serialized expression
even for valid blobs, if there is a conflict in symbol fixities between
the symbol tables of the sending and the receiving process. To avoid
this, make sure that symbol declarations in the sending and the receiving
script match up.
Other Special Primitives
.. raw:: html
<a name="exit">
.. _exit:
``exit status``
Terminate the program with the given status code.
.. raw:: html
<a name="throw">
.. _throw:
``throw x``
Throw an exception, cf. `Exception Handling`_.
.. _Exception Handling: pure.html#exception-handling
``force x``
Force a thunk (``x&``), cf. `Special Forms`_. This usually happens
automagically when the value of a thunk is needed.
.. _Special Forms: pure.html#special-forms
Pointer Operations
These are lowlevel operations dealing with pointer values. The usual
caveats apply, so *only* use these directly if you know what you're doing!
.. raw:: html
<a name="addr">
.. _addr:
``addr symbol``
Get the address of a C symbol (given as a string) at runtime. The library
containing the symbol must already be loaded. Note that this can in fact
be any kind of externally visible C symbol, so it's also possible to get
the addresses of global variables. The result is returned as a
pointer. The function fails if the symbol was not found.
.. raw:: html
<a name="calloc">
.. raw:: html
<a name="malloc">
.. raw:: html
<a name="realloc">
.. raw:: html
<a name="free">
.. _calloc:
.. _malloc:
.. _realloc:
.. _free:
``calloc nmembers size``, ``malloc size``, ``realloc ptr size``, ``free ptr``
Interface to ``malloc``, ``free`` and friends. These let you allocate
dynamic buffers (represented as Pure pointer values) for various nasty
.. raw:: html
<a name="get_byte">
.. raw:: html
<a name="get_short">
.. raw:: html
<a name="get_int">
.. raw:: html
<a name="get_int64">
.. raw:: html
<a name="get_long">
.. raw:: html
<a name="get_float">
.. raw:: html
<a name="get_double">
.. raw:: html
<a name="get_string">
.. raw:: html
<a name="get_pointer">
.. raw:: html
<a name="put_byte">
.. raw:: html
<a name="put_short">
.. raw:: html
<a name="put_int">
.. raw:: html
<a name="put_int64">
.. raw:: html
<a name="put_long">
.. raw:: html
<a name="put_float">
.. raw:: html
<a name="put_double">
.. raw:: html
<a name="put_string">
.. raw:: html
<a name="put_pointer">
.. _get_byte:
.. _get_short:
.. _get_int:
.. _get_int64:
.. _get_long:
.. _get_float:
.. _get_double:
.. _get_string:
.. _get_pointer:
.. _put_byte:
.. _put_short:
.. _put_int:
.. _put_int64:
.. _put_long:
.. _put_float:
.. _put_double:
.. _put_string:
.. _put_pointer:
The following operations perform direct memory accesses. Use with care
... or else!
* ``get_byte ptr``, ``get_short ptr``, ``get_int ptr``, ``get_int64 ptr``,
``get_long ptr``, ``get_float ptr``, ``get_double ptr``,
``get_string ptr``, ``get_pointer ptr``
* ``put_byte ptr x``, ``put_short ptr x``, ``put_int ptr x``,
``put_int64 ptr x``, ``put_long ptr x``, ``put_float ptr x``,
``put_double ptr x``, ``put_string ptr x``, ``put_pointer ptr x``
Sentries are Pure's flavour of object `finalizers`. A sentry is simply an
object (usually a function) which gets applied to the target expression
when it is garbage-collected. This is useful to perform automatic cleanup
actions on objects with internal state, such as files. Pure's sentries are
*much* more useful than finalizers in other garbage-collected languages,
since it is guaranteed that they are called as soon as an object "goes out
of scope", i.e., becomes inaccessible.
.. raw:: html
<a name="sentry">
.. _sentry:
``sentry f x``
Places a sentry ``f`` at an expression ``x`` and returns the modified
.. raw:: html
<a name="clear_sentry">
.. _clear_sentry:
``clear_sentry x``
Removes the sentry from an expression ``x``.
.. raw:: html
<a name="get_sentry">
.. _get_sentry:
``get_sentry x``
Returns the sentry of an expression ``x`` (if any, fails otherwise).
Note that in the current implementation sentries can only be placed at
symbols, applications, as well as function and pointer objects, but the
department of fake statistics has assured us that this covers 99.7% of all
practical uses. The sentry itself can be any type of object (but usually
it's a function).
> using system;
> sentry (\_->puts "Hello, world!") (1..3);
> clear ans
Hello, world!
Note that setting a finalizer on a global symbol won't usually be of much
use since such values are cached by the interpreter. (However, the sentry
*will* be invoked if the symbol gets recompiled because its definition
has changed. This may be useful for some purposes.)
One common case where sentries are particularly useful are pointers. The
library provides some special support for these by means of the following
.. raw:: html
<a name="cooked">
.. _cooked:
``cooked ptr``
Create a `cooked` pointer which disposes itself after use. This is just a
shorthand for ``sentry free``. The given pointer ``ptr`` must be
|malloc|_\ ed to make this work.
.. |malloc| replace:: ``malloc``
.. raw:: html
<a name="cookedp">
.. _cookedp:
``cookedp ptr``
Check whether a given pointer is cooked (this predicate actually assumes
any pointer to be cooked which has a sentry set on it).
> using system;
> let p = sentry (\p->puts "I'm done for!" $$ free p) (malloc 1024);
> cookedp p;
> clear p
I'm done for!
Besides their use as finalizers, sentries can also be handy in other
circumstances, when you need to associate an expression with another,
"invisible" value. In this case the sentry is usually some kind of data
structure instead of a function to be executed at finalization time. For
instance, here's how we can employ sentries to implement hashing of
function values::
using dict;
hashed f x = case get_sentry f of
h::HDict = h!x if member h x;
_ = y when y = f x; sentry (update h x y) f
when h = case get_sentry f of
h::HDict = h; _ = emptyhdict
E.g., consider the naive recursive definition of the Fibonacci function::
fib n::int = if n<=1 then 1 else fib (n-1)+fib (n-2);
A hashed version of the Fibonacci function can be defined as follows::
let hfib = hashed f with
f n::int = if n<=1 then 1 else hfib (n-1)+hfib (n-2)
This turns the naive definition of the Fibonacci function (which has
exponential time complexity) into a linear time operation::
> stats
> fib 35;
> hfib 35;
Finally, note that there can be only one sentry per expression but,
building on the operations provided here, it's easy to design a scheme
where sentries are chained. For instance::
chain_sentry f x = sentry (h (get_sentry x)) x with
h g x = g x $$ f x;
This invokes the original sentry before the chained one::
> using system;
> f _ = puts "sentry#1"; g _ = puts "sentry#2";
> let p = chain_sentry g $ sentry f $ malloc 10;
> clear p
You can chain any number of sentries that way::
> h _ = puts "sentry#3";
> let p = chain_sentry h $ chain_sentry g $ sentry f $ malloc 10;
> clear p
This scheme should work in most cases in which sentries are used just as
finalizers. However, there are other uses, like the "hashed function"
example above, where you'd like the original sentry to stay intact. This
can be achieved by placing the new sentry as a sentry on the *original
sentry* rather than the expression itself::
attach_sentry f x = sentry (sentry f (get_sentry x)) x;
Of course, this assumes that the original sentry is something that you can
place a sentry on. It also requires that the sentry will actually be
garbage-collected when its hosting expression gets freed, so it will *not*
work if the original sentry is a global::
> let p = chain_sentry g $ sentry f $ malloc 10;
> clear p
However, the attached sentry will work ok if you can ensure that the
original sentry is a (partial or constructor) application, which also
encompasses most kinds of aggregate Pure data. E.g.::
> let p = chain_sentry g $ sentry (f$) $ malloc 10;
> clear p
Expression References
Expression references provide a kind of mutable data cells which can hold
any Pure expression. If you need these, then you're doomed. ;-) However,
they can be useful as a last resort when you need to keep track of some
local state or interface to the messy imperative world. Pure's references
are actually implemented as expression pointers so that you can readily
pass them as pointers to a C function which expects a ``pure_expr**``
parameter. This may even be useful at times.
.. raw:: html
<a name="ref">
.. _ref:
``ref x``
Create a reference pointing to ``x`` initially.
.. raw:: html
<a name="put">
.. _put:
``put r x``
Set a new value ``x``, and return that value.
.. raw:: html
<a name="get">
.. _get:
``get r``
Retrieve the current value ``r`` points to.
.. raw:: html
<a name="unref">
.. _unref:
``unref r``
Purge the referenced object and turn the reference into a dangling
pointer. (This is used as a sentry on reference objects and shouldn't
normally be called directly.)
.. raw:: html
<a name="refp">
.. _refp:
``refp x``
Predicate to check for reference values.
Note that manually removing the ``unref`` sentry of a reference turns the
reference into just a normal pointer object and renders it unusable as a
reference. Doing this will also leak memory, so don't!
Mathematical Functions
The math.pure module provides Pure's basic math routines. It also defines
complex and rational numbers.
To use the operations of this module, add the following import declaration
to your program::
using math;
Basic Math Functions
The module defines Euler's number ``e = 2.71828...`` and Ludolph's number
``pi = 3.1415...`` as constants. It also provides a reasonably
comprehensive (pseudo) random number generator which uses the `Mersenne
twister`_ to avoid bad generators present in some C libraries.
Please note that as of Pure 0.41, the runtime library includes a newer
release of the Mersenne twister which fixes issues with some kinds of seed
values, and will yield different values for given seeds. Also, the
``random31`` and ``random53`` functions have been added as a convenience to
compute unsigned 31 bit integers and 53 bit double values, and the
``srandom`` function now also accepts an ``int`` matrix as seed value.
.. _Mersenne twister:
.. raw:: html
<a name="random">
.. _random:
Return 32 bit pseudo random ints in the range ``-0x80000000..0x7fffffff``.
.. raw:: html
<a name="random31">
.. _random31:
Return 31 bit pseudo random ints in the range ``0..0x7fffffff``.
.. raw:: html
<a name="random53">
.. _random53:
Return pseudo random doubles in the range ``[0,1)`` with 53 bits
.. raw:: html
<a name="srandom">
.. _srandom:
``srandom seed``
Sets the seed of the generator to the given 32 bit integer. You can also
specify longer seeds using a nonempty row vector, e.g.: ``srandom {0x123,
0x234, 0x345, 0x456}``.
The following functions work with both double and int/bigint arguments. The
result is always a double. For further explanations please see the
descriptions of the corresponding functions from the C math library.
.. raw:: html
<a name="sqrt">
.. _sqrt:
``sqrt x``
The square root function.
.. raw:: html
<a name="exp">
.. raw:: html
<a name="ln">
.. raw:: html
<a name="log">
.. _exp:
.. _ln:
.. _log:
``exp x``, ``ln x``, ``log x``
Exponential function, natural and decadic logarithms.
.. raw:: html
<a name="sin">
.. raw:: html
<a name="cos">
.. raw:: html
<a name="tan">
.. _sin:
.. _cos:
.. _tan:
``sin x``, ``cos x``, ``tan x``
Trigonometric functions.
.. raw:: html
<a name="asin">
.. raw:: html
<a name="acos">
.. raw:: html
<a name="atan">
.. _asin:
.. _acos:
.. _atan:
``asin x``, ``acos x``, ``atan x``
Inverse trigonometric functions.
.. raw:: html
<a name="atan2">
.. _atan2:
``atan2 y x``
Computes the arcus tangent of ``y/x``, using the signs of the two
arguments to determine the quadrant of the result.
.. raw:: html
<a name="sinh">
.. raw:: html
<a name="cosh">
.. raw:: html
<a name="tanh">
.. _sinh:
.. _cosh:
.. _tanh:
``sinh x``, ``cosh x``, ``tanh x``
Hyperbolic trigonometric functions.
.. raw:: html
<a name="asinh">
.. raw:: html
<a name="acosh">
.. raw:: html
<a name="atanh">
.. _asinh:
.. _acosh:
.. _atanh:
``asinh x``, ``acosh x``, ``atanh x``
Inverse hyperbolic trigonometric functions.
Complex Numbers
.. raw:: html
<a name="+:">
.. raw:: html
<a name="<:">
.. _+\::
.. _<\::
We provide both rectangular (``x+:y``) and polar (``r<:a``)
representations, where ``(x,y)`` are the Cartesian coordinates and
``(r,t)`` the radius (absolute value) and angle (in radians) of a complex
number, respectively. The ``+:`` and ``<:`` constructors (declared in the
prelude) bind weaker than all other arithmetic operators and are
The polar representation ``r<:t`` is normalized so that ``r`` is always
nonnegative and ``t`` falls in the range ``-pi<t<=pi``.
The constant ``i`` is provided to denote the imaginary unit ``0+:1``.
The arithmetic operations ``+``, ``*`` etc. and the equality relations
``==`` and ``~=`` work as expected, and the square root, exponential,
logarithms, trigonometric and hyperbolic trigonometric functions (see
`Basic Math Functions`_) are extended to complex numbers accordingly. These
do *not* rely on complex number support in the C library, but should still
conform to IEEE 754 and POSIX, provided that the C library provides a
standards-compliant implementation of the basic math functions.
The following operations all work with both the rectangular and the polar
representation, promoting real (double, int/bigint) inputs to complex where
appropriate. When the result of an operation is again a complex number, it
generally uses the same representation as the input (except for explicit
conversions). Mixed rect/polar and polar/rect arithmetic always returns a
rect result, and mixed complex/real and real/complex arithmetic yields a
rect or polar result, depending on what the complex input was.
.. raw:: html
<a name="complex">
.. _complex:
``complex x``
Convert any kind of number to a complex value.
.. raw:: html
<a name="polar">
.. raw:: html
<a name="rect">
.. _polar:
.. _rect:
``polar z``, ``rect z``
Convert between polar and rectangular representations.
.. raw:: html
<a name="cis">
.. _cis:
``cis t``
Create complex values on the unit circle. Note: To quickly compute
``exp (x+:y)`` in polar form, use ``exp x <: y``.
.. raw:: html
<a name="abs (complex)">
.. raw:: html
<a name="arg">
.. _abs (complex):
.. _arg:
``abs z``, ``arg z``
Modulus (absolute value) and argument (angle, a.k.a. phase). Note that
you can also find both of these in one go by converting to polar form.
.. raw:: html
<a name="re">
.. raw:: html
<a name="im">
.. _re:
.. _im:
``re z``, ``im z``
Real and imaginary part.
.. raw:: html
<a name="conj">
.. _conj:
``conj z``
Complex conjugate.
> using math;
> let z = 2^(1/i); z;
> let z = ln z/ln 2; z;
> abs z, arg z;
> polar z;
Please note that, as the ``+:`` and ``<:`` constructors bind weaker than
the other arithmetic operators, complex numbers *must* be parenthesized
accordingly, e.g.::
> (1+:2)*(3+:4);
Rational Numbers
.. raw:: html
<a name="%">
.. _%:
Pure's rational numbers are constructed with the `exact division` operator
``%`` (declared in the prelude) which has the same precedence and fixity as
the other division operators.
The ``%`` operator returns a rational or complex rational for any
combination of integer, rational and complex integer/rational arguments,
provided that the denominator is nonzero (otherwise it behaves like ``x div
0``, which will raise an exception). Machine int operands are always
promoted to bigints, thus normalized rationals always take the form ``x%y``
where both the numerator ``x`` and the denominator ``y`` are bigints. For
other numeric operands ``%`` works just like ``/``. Rational results are
normalized so that the sign is always in the numerator and numerator and
denominator are relatively prime. In particular, a rational zero is always
represented as ``0L%1L``.
The usual arithmetic operations and equality/order relations are extended
accordingly, as well as the `basic math functions`_ and the `rounding
functions`_, and will return exact (rational or complex rational) results
where appropriate. Rational operations are implemented using the GMP
bigint functions where possible, and thus are reasonably fast.
In addition, the module also provides following operations:
.. raw:: html
<a name="rational">
.. _rational:
``rational x``
Converts a real or complex value ``x`` to a rational or complex
rational. Note that the conversion from double values doesn't do any
rounding, so it is guaranteed that converting the resulting rational back
to a double reconstructs the original value.
Conversely, the |int|_, |bigint|_, |double|_, |complex|_, |rect|_,
|polar|_ and |cis|_ conversion functions are overloaded so that they
convert a rational to one of the other number types.
.. |int| replace:: ``int``
.. |bigint| replace:: ``bigint``
.. |double| replace:: ``double``
.. |complex| replace:: ``complex``
.. |rect| replace:: ``rect``
.. |polar| replace:: ``polar``
.. |cis| replace:: ``cis``
.. raw:: html
<a name="num">
.. raw:: html
<a name="den">
.. _num:
.. _den:
``num x``, ``den x``
Numerator and denominator of a rational ``x``.
> using math;
> 5%7 + 2%3;
> 3%8 - 1%3;
> pow (11%10) 3;
> let x = pow 3 (-3); x;
> num x, den x;
> rational (3/4);
Note that doubles can't represent most rationals exactly, so conversion
from double to rational *will* yield funny results in many cases (which are
still accurate up to rounding errors). For instance::
> let x = rational (1/17); x;
> num x/den x;
> double (1%17);
Semantic Number Predicates
In difference to the syntactic predicates in Primitives_, these check
whether the given value can be represented as an object of the given target
type (up to rounding errors). Note that if ``x`` is of syntactic type
``X``, then it is also of semantic type ``X``. Moreover, ``intvalp x =>
bigintvalp x => ratvalp x => realvalp x => compvalp x <=> numberp x``.
.. raw:: html
<a name="compvalp">
.. _compvalp:
``compvalp x``
Check for complex values (this is the same as |numberp|_).
.. |numberp| replace:: ``numberp``
.. raw:: html
<a name="realvalp">
.. _realvalp:
``realvalp x``
Check for real values (``im x==0``).
.. raw:: html
<a name="ratvalp">
.. _ratvalp:
``ratvalp x``
Check for rational values (same as ``realvalp``, except that IEEE 754
infinities and NaNs are excluded).
.. raw:: html
<a name="bigintvalp">
.. _bigintvalp:
``bigintvalp x``
Check for "big" integer values which can be represented as a bigint.
.. raw:: html
<a name="intvalp">
.. _intvalp:
``intvalp x``
Check for "small" integer values which can be represented as a machine
Container Types
The standard library provides a variety of efficient container data
structures for different purposes. These are all purely functional, i.e.,
immutable data structures implemented using different flavours of binary
trees. This means that instead of modifying a data structure in-place,
operations like insertion and deletion return a new instance of the
container, keeping the previous instance intact. Nevertheless, all
operations are performed efficiently, in logarithmic time where possible.
The container types are all implemented as abstract data structures, so
client modules shouldn't rely on the internal representation. Each type
provides a corresponding type tag (cf. `Type Tags`_ in the Pure Manual), as
given in the "Data Structure" section of each type, which can be used to
match values of the type, e.g.::
shift a::Array = rmfirst a;
.. _Type Tags: pure.html#type-tags
All container types implement the equality predicates ``==`` and ``~=`` by
recursively comparing their members. In addition, the dictionary, set and
bag data structures also provide the other comparison predicates (``<``,
``<=`` etc.) which check whether one dictionary, set or bag is contained in
The array.pure module implements an efficient functional array data
structure which allows to access and update individual array members, as
well as to add and remove elements at the beginning and end of an
array. All these operations are carried out in logarithmic time.
To use the operations of this module, add the following import declaration
to your program::
using array;
Data Structure
Arrays are represented as balanced tree structures of the form ``Array T``,
thus ``Array`` may be used as a type tag to restrict variables in pattern
The internal data structure ``T`` is a binary tree built with the following
the empty tree.
``array::tip value``
a leaf of the tree, holding the given value.
``array::bin balance left right``
a nonempty tree with the given balance flag (0 or 1) and left and right
(This is for informational purposes only. The tree constructors are
private, and client modules must not rely on the internal representation.)
.. raw:: html
<a name="emptyarray">
.. _emptyarray:
return the empty array
.. raw:: html
<a name="array">
.. _array:
``array xs``
create an array from a list ``xs``
.. raw:: html
<a name="array2">
.. _array2:
``array2 xs``
create a two-dimensional array from a list of lists
.. raw:: html
<a name="mkarray">
.. _mkarray:
``mkarray x n``
create an array consisting of ``n`` ``x``'s
.. raw:: html
<a name="mkarray2">
.. _mkarray2:
``mkarray2 x (n,m)``
create a two-dimensional array of ``n*m`` ``x``'s
.. raw:: html
<a name="arrayp">
.. _arrayp:
``arrayp x``
check whether ``x`` is an array
.. raw:: html
<a name="# (array)">
.. _# (array):
size of ``a``
.. raw:: html
<a name="! (array)">
.. _! (array):
return the ``i``\ th member of ``a``
two-dimensional subscript
.. raw:: html
<a name="null (array)">
.. _null (array):
``null a``
test whether ``a`` is the empty array
.. raw:: html
<a name="members (array)">
.. raw:: html
<a name="list (array)">
.. _members (array):
.. _list (array):
``members a``, ``list a``
list of values stored in ``a``
.. raw:: html
<a name="members2 (array)">
.. raw:: html
<a name="list2 (array)">
.. _members2 (array):
.. _list2 (array):
``members2 a``, ``list2 a``
list of members in a two-dimensional array
.. raw:: html
<a name="first (array)">
.. raw:: html
<a name="last (array)">
.. _first (array):
.. _last (array):
``first a``, ``last a``
first and last member of ``a``
.. raw:: html
<a name="rmfirst (array)">
.. raw:: html
<a name="rmlast (array)">
.. _rmfirst (array):
.. _rmlast (array):