Iterative constructs (for, while)
> | for i from 1 to 4 do i^2; od; |
> | l:=[]; |
> | for i from 1 to 4 do l:=[op(l),i^2]; od; |
> | i:=1; |
> | while i+2 < 6 do i:=i+1: od; |
Functions
> | f:=x->x+1; |
> | f(2); |
> | type(f,'function'); type(cos(x),'function'); |
> | whattype(f); |
The operators @ and @@ are used to compose functions
> | (f@f)(2); |
> | (f@@5)(2); |
> | g:=y->y+2; |
> | (f@g)(x); |
> | ((f@g)@@3)(x); |
> | h:=(x,y,z)->x^2+y^2-z^2; |
> | h(3,4,5); |
Recursive functions (factorial, Fibonacci)
> | fact:=n->if n = 0 then 1; else n*f(n-1); fi; |
> | fact(3); fact(7); |
> | fibo:=n->if n = 0 then 0 elif n = 1 then 1 else fibo(n-1)+fibo(n-2); fi; |
> | seq(fibo(i),i=0..12); |
> | phi := (1+sqrt(5))/2; Phi := (1-sqrt(5))/2; |
> | fibo1:=n->(phi^n-Phi^n)/(sqrt(5)); |
> | fibo1(100); |
> | expand(%); |
> | seq(fibo(i)-expand(fibo1(i)),i=1..10); |
> | time(fibo(25)); |
> | time(expand(fibo1(500))); |
Procedures
> | f:=proc(x) x^2; end; |
> | f(3); |
> | ff:=proc(n,g) local aux,i; aux:=[seq(i^2,i=1..n)]; map(g,aux); end proc; |
> | ff(3,f); |
The option remember updates the remember table
> | fib := proc(n) option remember; if n<2 then n else fib(n-1)+fib(n-2) end if; end proc; |
> | st:=time(): fib(100); time()-st; |
Accessing the remember table
> | op(4,eval(fib)); |
> | op(4,eval(cos)); |
> | cos(Pi/12):=1/4*sqrt(6)+1/4*sqrt(2); |
> | op(4,eval(cos)); |
> | cos(Pi/12); |