for_loop.anubis.c 1.99 KB

   /*
 *Project*                             The Anubis Project
   
 *Title*               
   
 *Copyright*                     Copyright (c) Alain Prouté 2005. 
  
 *Released*  
   
   How to make a 'for' loop (a la C) in Anubis. 
   
   
   
   C version (with one state variable 'x'): 
   
   for( x = init ; cond(x) ; x = step(x) )
     instruction(x)
   
   Before this loop is entered, the value of  x is init. While 'cond(x)' is true, the body
   of the  loop is executed, and the  value of x is  changed by 'x =  step(x)'.  The first
   time 'cond(x)' is not true when we reenter the loop. the loop is exited. 

   
   Anubis version (the value of this term is the value of x when the C loop is exited): 
   
    ((T x) |-f-> if cond(x) 
                 then (instruction(x); f(step(x))) 
                 else x)(init)

   The symbol '|-f->'  constructs an anonymous recursive function, using  the name 'f' for
   its own recursive calls.  This function reveives one argument 'x' of some type 'T'.  It
   is applied to the  initial value of 'x', namely 'init', and  returns the final value of
   'x'.  It first tests  'x' with 'cond(x)'. If the result is  false, the current value of
   'x' is returned by  'else x' (the loop is exited).  If  it is true, 'instruction(x)' is
   executed,  and the  recursive  function is  called again  with  the new  value of  'x':
   'step(x)'.  So, actually the execution is the same as in C.
   
   
   Working example:
 
   */
   
main()
   {
   int x; 
   
   for (x = 0; x <= 10; x = x+1)
     {
       printf("%d ",x);
     }
   printf("\nresult = %d\n",x); 
   }
   
   /*
   
global define One
   for_loop_example
     (
       List(String) args
     ) =
   with x = ((Word32 x) |-f-> if x -=< 10
                              then (print(to_decimal(x)+" "); f(x+1))
                              else x)(0), 
     print("\nresult = "+to_decimal(x)+"\n"). 
  
   
   
   These two programs produce the same result:
   
0 1 2 3 4 5 6 7 8 9 10
result = 11   
   
   */