Pure (programming language): Difference between revisions

Content deleted Content added
Unicas (talk | contribs)
Tag: Reverted
Unicas (talk | contribs)
Tag: Reverted
Line 85:
</syntaxhighlight>
 
Pure has efficient support for vectors and matrices (similar to that of [[MATLAB]] and [[GNU Octave]]), including vector and matrix comprehensions. E.g., a [[Gaussian elimination]] algorithm with [[partial pivoting]] can be implemented in Pure thus:
 
Namespaces, types and interfaces belong to the standard repertoire:
 
<syntaxhighlight lang="q">
nonfix nil;
gauss_elimination x::matrix = p,x
type bintree nil | bintree (bin x left right);
when n,m = dim x; p,_,x = foldl step (0..n-1,0,x) (0..m-1) end;
 
outfix « »;
namespace foo (« »);
infixr (::^) ^;
x^y = 2*x+y;
namespace;
 
interface stack with
step (p,i,x) j
push s::stack x;
= if max_x==0 then p,i,x else
pop s::stack;
// updated row permutation and index:
top s::stack;
transp i max_i p, i+1,
{// the top rows of the matrix remain unchanged:
x!!(0..i-1,0..m-1);
// the pivot row, divided by the pivot element:
{x!(i,l)/x!(i,j) | l=0..m-1};
// subtract suitable multiples of the pivot row:
{{x!(k,l)-x!(k,j)*x!(i,l)/x!(i,j) | k=i+1..n-1; l=0..m-1}}
when
n,m = dim x; max_i, max_x = pivot i (col x j);
x = if max_x>0 then swap x i max_i else x;
end with
pivot i x = foldl max (0,0) [j,abs (x!j)|j=i..#x-1];
max (i,x) (j,y) = if x<y then j,y else i,x;
end;
 
type stack [];
/* Swap rows i and j of the matrix x. */
 
push xs@[] x | push xs@(_:_) x = x:xs;
swap x i j = x!!(transp i j (0..n-1),0..m-1) when n,m = dim x end;
pop (x:xs) = xs;
 
top (x:xs) = x;
/* Apply a transposition to a permutation. */
 
transp i j p = [p!tr k | k=0..#p-1]
with tr k = if k==i then j else if k==j then i else k end;
 
/* Example: */
 
let x = dmatrix {2,1,-1,8; -3,-1,2,-11; -2,1,2,-3};
x; gauss_elimination x;
</syntaxhighlight>
 
 
As a language based on [[term rewriting]], Pure fully supports [[symbolic computation]] with expressions. Here is an example showing the use of local rewriting rules to [[polynomial expansion|expand]] and [[factorization|factor]] simple arithmetic expressions:
Line 148 ⟶ 137:
hello;
</syntaxhighlight>
 
Instead of manually compiling source files to LLVM bitcode modules, one can also place the source code into a Pure script, enclosing it in %< ... %> (inline code, e.g. C, Fortran 77/90 and so on).
 
==See also==