Scheme for Java Programmer

From CDOT Wiki
Revision as of 18:04, 8 March 2011 by Tpcheun1 (talk | contribs)
Jump to: navigation, search
String
 
>>>> in Java
String st = new String("Seneca");
st = st.replace("e", "u");
System.out.println(st);  // Sunuca

>>>> in Scheme
(define st (java.lang.String'new "Seneca"))
(set! st (st'replace "e" "u" ))
(display st)  ; Sunuca

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
if

>>>> in Java
int x = 3, y = 5, large = 0;
if (x > y)
    large = x;
else
    large = y;

System.out.print(large);  // 5

>>>> in Scheme
(define x 3)
(define y 5)
(define large 0)

(if (> x y)
   (set! large x)
   (set! large y)
)
(display large) ; 5

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
for

>>>> in Java
for (int i = 0; i < 10; i++)
    System.out.print(i);  // 0123456789


>>>> in Scheme
(for ((i 0)) (< i 10) (set! i (+ i 1))
   (display i)  ; 0123456789
)
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
While

>>>> in Java
int n = 0;
while(n < 10){
    System.out.print(n);
    n++;
}
// 0123456789

>>>> in Scheme
(define n 0)

(while (< n 10)
   (display n)
   (set! n (+ n 1))
)
; 0123456789


- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Switch Case

>>>> in Java
int x = 7;
String st = "";
switch (x){
    case 1: st = "one";    break;
    case 3: st = "three";  break;
    case 7: st = "seven";  break;
    default: st = "else";
}
System.out.println(st);

>>>> in Scheme
(define x 7)
(define st "")

(case x
   ((1) (set! st 'one))
   ((3) (set! st 'three))
   ((7) (set! st 'seven))
   (else (set! st 'else))
)

(display st) ; seven


- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Iterator

>>>> in Java
ArrayList numbers = new ArrayList();

for (int i = 0; i < 10; i++)
    numbers.add(i);

for (Iterator iterator = numbers.iterator(); iterator.hasNext();)
    System.out.print(iterator.next());    //  0123456789


>>>> in Scheme
(import 'java.util.ArrayList)
(define numbers (java.util.ArrayList'new))

(for ((i 0)) (< i 10) (set! i (+ i 1))
   (numbers'add i)
)

(for ((it (numbers'iterator))) (it'hasNext) ()
   (write (it'next)) ; 0123456789
)

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Try and Catch

>>>> in Java

try {
    int x = 1 /0;
} catch (ArithmeticException e) {
    e.printStackTrace();
} finally{
    System.out.println("finally");
}
// java.lang.ArithmeticException: / by zero
//  finally

>>>> in Scheme
(try
   (define x (/ 1 0))
   (lambda (e) e)
   (display "finally")
)
; final
; #<java.lang.ArithmeticException: / by zero>