2010年10月15日 星期五

Mathematica研究:常用的rule 和 functional program,以Quick Sort 為例

一行實現quick sort演算法:
QuickSort[l_List] :=
l /. {x_, y__} :>
Join @@ QuickSort /@ {Select[{y}, # < x &], {x},
Select[{y}, # >= x &]}


/. :expr/.rules
applies a rule or list of rules in an attempt to transform each
subpart of an expression expr.

_ :_ or Blank[]
is a pattern object that can stand for any Mathematica expression.
x_ gives a name to _ as x
x:{pattern} gives a name to pattern as x


__
:__ (two _ characters) or BlankSequence[]
is a pattern object that can stand for any sequence of one or more
Mathematica expressions.

___ :___ (three _ characters) or BlankNullSequence[]
is a pattern object that can stand for any sequence of zero or more \
Mathematica expressions.

.. :p.. or Repeated[p]
is a pattern object which represents a sequence of one or more \
expressions, each matching p.

:> :lhs:>rhs or lhs:>rhs
represents a rule that transforms lhs to rhs, evaluating rhs only
after the rule is used.

@@ :Apply[f,expr]
or f@@expr replaces the head of expr by f.

/@ :Map[f,expr] or f/@expr
applies f to each element on the first level in expr.

& :Function[body]
or body& is a pure function. The formal parameters are # (or #1), #2, etc.

沒有留言: