Chapitre 12. Exemple de programmes en GEL

Voici une fonction qui calcule des factorielles :

function f(x) = if x <= 1 then 1 else (f(x-1)*x)

Avec des indentations, cela devient :

function f(x) = (
  if x <= 1 then
    1
  else
    (f(x-1)*x)
)

C'est un portage direct de la fonction factorielle de la page de manuel de bc. La syntaxe semble similaire à celle de bc mais différente par le fait que dans GEL, la dernière expression est celle qui est renvoyée. En utilisant la fonction return à la place, cela donnerait :

function f(x) = (
  if (x <= 1) then return (1);
  return (f(x-1) * x)
)

La façon, de loin la plus facile, de définir une fonction factorielle serait d'utiliser la boucle de produit de la manière suivante. Ce n'est pas seulement la plus courte et la plus rapide mais aussi probablement la version la plus lisible.

function f(x) = prod k=1 to x do k

Here is a larger example, this basically redefines the internal ref function to calculate the row echelon form of a matrix. The function ref is built in and much faster, but this example demonstrates some of the more complex features of GEL.

# Calculate the row-echelon form of a matrix
function MyOwnREF(m) = (
  if not IsMatrix(m) or not IsValueOnly(m) then
    (error("MyOwnREF: argument not a value only matrix");bailout);
  s := min(rows(m), columns(m));
  i := 1;
  d := 1;
  while d <= s and i <= columns(m) do (

    # This just makes the anchor element non-zero if at
    # all possible
    if m@(d,i) == 0 then (
      j := d+1;
      while j <= rows(m) do (
        if m@(j,i) == 0 then
          (j=j+1;continue);
        a := m@(j,);
        m@(j,) := m@(d,);
        m@(d,) := a;
        j := j+1;
        break
      )
    );
    if m@(d,i) == 0 then
      (i:=i+1;continue);
    
    # Here comes the actual zeroing of all but the anchor
    # element rows
    j := d+1;
    while j <= rows(m)) do (
      if m@(j,i) != 0 then (
        m@(j,) := m@(j,)-(m@(j,i)/m@(d,i))*m@(d,)
      );
      j := j+1
    );
    m@(d,) := m@(d,) * (1/m@(d,i));
    d := d+1;
    i := i+1
  );
  m
)