Pure (programming language): Difference between revisions

Content deleted Content added
m Examples: Typo.
No edit summary
Line 35:
 
<pre>
fib 0 = 0;
fib 1 = 1;
fib n = fib (n-2) + fib (n-1) if n>1;
</pre>
 
Line 43:
 
<pre>
fib n = fibs (0,1) n with
fibs (a,b) n = if n<=0 then a else fibs (b,a+b) (n-1);
end;
</pre>
 
Line 51:
 
<pre>
map fib (1..20);
</pre>
 
Line 57:
 
<pre>
queens n = search n 1 [] with
search n i p = [reverse p] if i>n;
= cat [search n (i+1) ((i,j):p) | j = 1..n; safe (i,j) p];
safe (i,j) p = ~any (check (i,j)) p;
check (i1,j1) (i2,j2)
= i1==i2 || j1==j2 || i1+j1==i2+j2 || i1-j1==i2-j2;
end;
</pre>
 
Line 69:
 
<pre>
primes = sieve (2..inf) with
sieve (p:qs) = p : sieve [q | q = qs; q mod p] &;
end;
</pre>
 
Line 77:
 
<pre>
primes!!(0..99); // yields the first 100 primes
</pre>
 
Line 83:
 
<pre>
gauss_elimination x::matrix = p,x
when n,m = dim x; p,_,x = foldl step (0..n-1,0,x) (0..m-1) end;
 
step (p,i,x) j
= if max_x==0 then p,i,x else
// updated row permutation and index:
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;
 
/* Swap rows i and j of the matrix x. */
 
swap x i j = x!!(transp i j (0..n-1),0..m-1) when n,m = dim x end;
 
/* 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;
</pre>
 
Line 122:
 
<pre>
expand = reduce with
(a+b)*c = a*c+b*c;
a*(b+c) = a*b+a*c;
end;
 
factor = reduce with
a*c+b*c = (a+b)*c;
a*b+a*c = a*(b+c);
end;
 
expand ((a+b)*2); // yields a*2+b*2
factor (a*2+b*2); // yields (a+b)*2
</pre>
 
Line 139:
 
<syntaxhighlight lang="c">
extern int puts(char*);
hello = puts "Hello, world!";
hello;
</syntaxhighlight>
 
Line 148:
* [[Functional programming]]
* [[:Category: Functional languages|Functional languages]]
* [[Clean (programming language)]]
 
== References ==