Content deleted Content added
No edit summary |
m <syntaxhighlight lang="q"> for pygments 2.12 upgrade |
||
Line 34:
The [[Fibonacci numbers]] (naive version):
<syntaxhighlight lang="q">
fib 0 = 0;
fib 1 = 1;
fib n = fib (n-2) + fib (n-1) if n>1;
</syntaxhighlight>
Better ([[tail-recursive]] and [[linear-time]]) version:
<syntaxhighlight lang="q">
fib n = fibs (0,1) n with
fibs (a,b) n = if n<=0 then a else fibs (b,a+b) (n-1);
end;
</syntaxhighlight>
Compute the first 20 Fibonacci numbers:
<syntaxhighlight lang="q">
map fib (1..20);
</syntaxhighlight>
An [[algorithm]] for the [[Eight queens puzzle|n queens problem]] which employs a [[list comprehension]] to organize the backtracking search:
<syntaxhighlight lang="q">
queens n = search n 1 [] with
search n i p = [reverse p] if i>n;
Line 64:
= i1==i2 || j1==j2 || i1+j1==i2+j2 || i1-j1==i2-j2;
end;
</syntaxhighlight>
While Pure uses [[eager evaluation]] by default, it also supports [[Lazy evaluation|lazy]] data structures such as streams (lazy [[List (computing)|lists]]). For instance, [[David Turner (computer scientist)|David Turner]]'s algorithm<ref>Turner, David A. SASL language manual. Tech. rept. CS/75/1. Department of Computational Science, University of St. Andrews 1975.</ref> for computing the stream of [[prime numbers]] by [[trial division]] can be expressed in Pure:
<syntaxhighlight lang="q">
primes = sieve (2..inf) with
sieve (p:qs) = p : sieve [q | q = qs; q mod p] &;
end;
</syntaxhighlight>
Use of the <code>&</code> operator turns the tail of the sieve into a [[thunk]] to delay its computation. The thunk is evaluated implicitly and then [[Memoization|memoized]] (using [[call by need]] evaluation) when the corresponding part of the list is accessed, e.g.:
<syntaxhighlight lang="q">
primes!!(0..99); // yields the first 100 primes
</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:
<syntaxhighlight lang="q">
gauss_elimination x::matrix = p,x
when n,m = dim x; p,_,x = foldl step (0..n-1,0,x) (0..m-1) end;
Line 117:
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:
<syntaxhighlight lang="q">
expand = reduce with
(a+b)*c = a*c+b*c;
Line 134:
expand ((a+b)*2); // yields a*2+b*2
factor (a*2+b*2); // yields (a+b)*2
</syntaxhighlight>
Calling [[C (programming language)|C]] functions from Pure is very easy. E.g., the following imports the <code>puts</code> function from the [[C library]] and uses it to print the string <code>"Hello, world!"</code> on the terminal:
|