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
,