소스 파일명: testWhile.ml

  1. (*
  2.  *  Filename: testWhile.ml
  3.  *
  4.  *  Purpose:  Example using the while loop syntax
  5.  *                while ....
  6.  * 
  7.  *  Execute: ocaml testWhile.ml -200 300
  8.  * 
  9.  *    Or
  10.  * 
  11.  *  Compile: ocamlc -o testWhile.exe testWhile.ml
  12.  *  Execute: testWhile -200 300
  13.  *)
  14. (* 사용법 표시 *)
  15. let printUsage() =
  16.     Printf.printf "Using: testWhile.py [integer1] [integer2]\n"; 
  17.     Printf.printf "This finds the greatest common divisor of the given two integers.\n";;
  18. let cmdArgs = Sys.argv;;
  19. if not ((Array.length cmdArgs) = 3) then
  20.     printUsage();;
  21. if not ((Array.length cmdArgs) == 3) then
  22.     exit 1;;
  23. (*
  24. // --------------------------------------
  25. // 명령행 인자의 두 스트링을 가져와서
  26. // 정수 타입으로 변환하여
  27. // 변수 val1과 val2에 저장한다.
  28. *)
  29. let val1 = int_of_string cmdArgs.(1);;
  30. let val2 = int_of_string cmdArgs.(2);;
  31. (* a는 |val1|, |val2| 중 큰 값 *)
  32. let a = ref (abs val1);;
  33. let b = ref (abs val2);;
  34. if (!a < !b) then
  35.     let t = !a in
  36.     a := abs val2;
  37.     b := t;;
  38. if (!b = 0) then
  39.     Printf.printf "GCD(%d, %d) = %d\n" val1 val2 !a;;
  40. if (!b = 0) then
  41.     exit 0;;
  42. (*
  43. // --------------------------------------
  44. // Euclidean 알고리즘의 시작
  45. //
  46. // a를 b로 나누어 몫은 q에, 나머지는 r에 저장
  47. *)
  48. let q = ref (!a / !b);;
  49. let r = ref (!a mod !b);;
  50. (*
  51. // --------------------------------------
  52. // Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
  53. *)
  54. while not (!r = 0) do
  55.     a := !b;
  56.     b := !r;
  57.     q := !a / !b;
  58.     r := !a mod !b;
  59. done;;
  60. (* 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다. *)
  61. let gcd = !b;;
  62. (* 최대공약수(GCD)를 출력한다. *)
  63. Printf.printf "GCD(%d, %d) = %d\n" val1 val2 gcd;;



컴파일:

Command> ocamlc -o testWhile.exe testWhile.ml

실행:

Command> testWhile
Using: TestWhile [integer1] [integer2]
This finds the greatest common divisor of the given two integers.

Command> testWhile -200 300
GCD(-200, 300) = 100

Command> testWhile -200 0
GCD(-200, 0) = 200

Command> testWhile 125 100
GCD(125, 100) = 25

Command> testWhile 23 25
GCD(23, 25) = 1



Posted by Scripter
,

OCaml 언어는 함수형 언어이면서도 명령형 언어의 특징을 대부분 가지고 잇다.
따라서 보통의 for 구문을 쓸 수도 있고, 재귀호출 함수릉 만들어 쓸 수도 있다.

아래의 소스에서 함수 printDan 은 보통의 for 구문을 쓴 것이고
함수 printAnotherDan 은 재귀호출 함수를 쓴 것이다.


소스 파일명: forTest.ml
------------------------------[소스 시작]
(*
   Filename: forTest.ml
 
   Execute: ocaml forTest.ml

     Or
 
   Compile: ocamlc -o forTest forTest.ml
   Execute: ./forTest
 
     Or
 
   Compile: ocamlc -o forTest.exe forTest.ml
   Execute: forTest
 
   Date: 2013. 1. 26.
   Copyright (c) pkim _AT_ scripts.pe.kr
*)

let printDan dan =
    for i = 1 to 9 do
        Printf.printf "%d x %d = %2d\n" dan i (dan*i)
    done;;

let printAnotherDan dan =
    let rec loop l =
        match l with
        [] -> []
        | x :: xs -> Printf.printf "%d x %d = %2d\n" dan x (dan*x); loop xs
    in
    loop (Array.to_list (Array.init 9 (fun x -> x + 1)));;
    (* loop [ 1; 2; 3; 4; 5; 6; 7; 8; 9 ];; *)


printDan 2;;
print_newline();;
printAnotherDan 3;;
print_newline();;
------------------------------[소스 끝]


컴파일> ocamlc -o forTest.exe forTest.ml

실행> forTest
2 x 1 =  2
2 x 2 =  4
2 x 3 =  6
2 x 4 =  8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18

3 x 1 =  3
3 x 2 =  6
3 x 3 =  9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27


 

Posted by Scripter
,

 

소스 파일명: testArguments.ml

  1. (*
  2.    Filename: testArguments.ml
  3.    Execute: ocaml testArguments.ml 1.2 2.1 3.00
  4.      Or
  5.    Compile: ocamlc -o testArguments testArguments.ml
  6.    Execute: ./pyramidOfDigits2 1.2 2.1 3.00
  7.      Or
  8.    Compile: ocamlc -o testArguments.exe testArguments.ml
  9.    Execute: testArguments 1.2 2.1 3.00
  10.    Date: 2013. 1. 26.
  11.    Copyright (c) pkim _AT_ scripts.pe.kr
  12. *)
  13. let main() =
  14.     let args = Sys.argv in
  15.     let args1 = Array.to_list args in
  16.     let arr1 = List.tl args1 in
  17.     let arr = List.map float_of_string arr1 in
  18.     Printf.printf "Count of arguments: %d\n" (List.length arr);
  19.     Printf.printf "The sum of arguments is %g\n" (List.fold_right (+.) arr 0.0);
  20.     print_newline();;
  21. main();;

 

컴파일> ocamlc -o testArguments.exe testArguments.nl

실행> testArguments 5.2 7.9 -1.21
Count of arguments: 3
The sum of arguments is 11.89


 

Posted by Scripter
,


소스 파일명: testIf.ml

  1. (*
  2.    Filename: testIf.ml
  3.    Execute: ocaml testIf.ml -8e-2
  4.      Or
  5.    Compile: ocamlc -o testIf.ml
  6.    Execute: ./testIf -8e-2
  7.      Or
  8.    Compile: ocamlc -o testIf.exe testIf.ml
  9.    Execute: testIf -8e-2
  10.    Date: 2013. 1. 26.
  11.    Copyright (c) pkim _AT_ scripts.pe.kr
  12. *)
  13. let printUsing() =
  14.      Printf.printf "Using: testIf [number]\n";
  15.      Printf.printf "   or  ./testIf [number]\n";
  16.      Printf.printf "   or  ocaml testIf.ml [number]\n";
  17.      Printf.printf "This determines whether the number is positive or not.\n";;
  18. let isPositve = function
  19.      | x when x > 0.0 -> "positive";
  20.      | x when x < 0.0 -> "negative" ;
  21.      | x when x = 0.0 -> "zero" ;
  22.      | _ -> "not a floating number";;
  23. let main () =
  24.     print_int(Array.length Sys.argv);;
  25.     if ((Array.length Sys.argv) < 2) then
  26.         printUsing()
  27.     else
  28.         let arg = float_of_string Sys.argv.(1) in
  29.         let msg = isPositve(arg) in
  30.         Printf.printf "%g is %s." arg msg;
  31.         print_newline();;
  32.     exit 0;;
  33. main ();;



컴파일> ocamlc -o testIf.exe testIf.ml

실행> testIf -1.2
-1.2 is negative.


실행> testIf 0.0
0 is zero.


실행> testIf -0.1e-127
-1e-128 is negative.


Posted by Scripter
,


컨솔에 문자 출력하는 ocaml 구문은

       Printf.printf "문자열(스트링)"

이다. 여기서 개행문자 "\n"을 추가하면 개행된다.
(Jython의 문자 출력 구문도 위와 같다.)
 
소스 파일명: hello.ml
------------------------------[소스 시작]
Printf.printf "%s, %s" "Hello" "world!\n";;

let name = "개똥이";;
Printf.printf "%s, %s!\n" "Hello" name;;

let name2 = ref "홍길동";;
let greeting = "안녕하세요?";;
name2 := "길동이";;
Printf.printf "%s, %s씨!\n" greeting !name2;;
------------------------------[소스 끝]


컴파일> ocamlc -o hello.exe hello.ml

실행> hello.exe
Hello, world!
Hello, 개똥이!
길동이씨! 안녕하세요?


* 또는 컴파일 옵션 -o 없이 컴파일하는 경우:
   이 때는 파일명이 ocamlprog.exe 실행파일이 생성된다.

컴파일> camlc hello.ml

실행> ocamlprog
Hello, world!
Hello, 개똥이!
길동이씨! 안녕하세요?



* 생성된 실행파일 hello.exe 는 ocamlrun 명령을 써서 실행하여도 된다.

실행> ocamlrun hello.exe
Hello, world!
Hello, 개똥이!
길동이씨! 안녕하세요?



* ocaml 명령을 사용하면 (컴파일 없이) 스크립트 소스를 바로 실행시킬 수 있다.

실행> ocaml hello.ml
Hello, world!
Hello, 개똥이!
길동이씨! 안녕하세요?



* GUI 환경에서 연습하기를 좋아한다면 OCamlWinPlus 를 사용해도 된다.




 



Posted by Scripter
,
소스파일명: hello.ml
open Printf;;

print_string "Hello, 안녕하세요?";;
print_endline "";;

let x = 23 in
let y = 7 in
printf "x의 값은 %d이고 y의 값은 %d입니다." x y;
print_endline "";
printf "따라서 그 곱은 x * y = %d * %d = %d 입니다.\n" x y (x*y);;


컴파일하기: ocamlc -o hello.exe hello.ml
실행 명령> hello
실행 결과:
Hello, 안녕하세요?
x의 값은 23이고 y의 값은 7입니다.
따라서 그 곱은 x * y = 23 * 7 = 161 입니다.


컴파일 없이 실행하기: ocaml hello.ml
실행 결과:

Hello, 안녕하세요?
x의 값은 23이고 y의 값은 7입니다.
따라서 그 곱은 x * y = 23 * 7 = 161 입니다.


 
 
Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,