TWiki . Doc . FiboNoviceExample

/*
From the command line
1) create a directory fibo
2) cd into directory fibo
3) save this source code as main.nice in directory fibo
4) compile the source code
   \fibo> nicec --sourcepath=.. -a fibo.jar fibo
5) run the jar file
   \fibo> java -jar fibo.jar 32
*/



void main(String[] args){
   println( fib( toSingleInt(args) ) ); 
}

int fib(int n){ 
   if (n < 2) return 1; else return fib(n-2) + fib(n-1);
}

int toSingleInt(String[] s){
   try { return Integer.parseInt(s[0]); }
   catch (Exception e){ return 1; } }



/* Notes - language

   Can you rewrite fib with a precondition?
      requires n >= 0;


*/

/* Notes - Compile & Run
The Nice compiler compiles PACKAGES (directories) not files, 
so we must tell the compiler which directory contains the 
package directory (fibo) not which directory contains
the file (main.nice).

   \projects> nicec fibo
   OK

   \projects\fibo> nicec --sourcepath=.. fibo
   OK

   \projects\fibo> nicec fibo
   FAILS! the compiler will try to find \projects\fibo\fibo



Let's make the compiler output to a jar file (fibo.jar):

   \projects\fibo> nicec --sourcepath=.. -a fibo.jar fibo
   nice.lang: parsing
   fibo: parsing
   fibo: typechecking
   fibo: generating code
   fibo: linking
   fibo: writing in archive
   nice.lang: writing in archive


Let's run the program:

   \projects\fibo> java -jar fibo.jar 
   1

   \projects\fibo> java -jar fibo.jar 32
   3524578
*/

-- IsaacGouy - 26 Aug 2003

If you like to program in a functional language style the fib function looks like:

// Definition with precondition and assertion message
int fib(int n) requires n >= 0 : "Fibonacci function is not defined for negative integers!";
// implementation with value dispatch
fib(0) = 1;
fib(1) = 1;
fib(n) = fib(n-2) + fib(n-1);

-- ChristianMayrhuber - 26 Nov 2004

----- Revision r1.11 - 03 Apr 2005 - 16:15 GMT - TWikiGuest
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.