printList 함수를 OCaml 의 함수형 언어의 특징을 살려 (꼬리 재귀호출과 match 표현을 이용하여) 구현하였다.

[파일명:  testSort.ml]------------------------------------------------
open Printf ;;

let printList data =
    let rec loop l =
        match l with
        | x::[] -> printf "%s" x
        | x::xs -> begin printf "%s, " x; loop xs end
        | [] -> printf ""
    in
        printf "[" ;
        loop data ;
        printf "]" ;;

(* Begin here *)
let cmdArgs = Sys.argv in
let args2 = Array.sub cmdArgs 1 ((Array.length cmdArgs) - 1) in
printf "Original data: " ;
printList (Array.to_list args2) ;
print_newline() ;

Array.sort String.compare args2 ;
printf "  Sorted data: " ;
let b = Array.to_list args2 in
printList b ;
print_newline() ;
------------------------------------------------


실행> ocaml testSort.ml a123 help me 한글 각자 halo kk c 564
Original data: [a123, help, me, 한글, 각자, halo, kk, c, 564]
  Sorted data: [564, a123, c, halo, help, kk, me, 각자, 한글]

Posted by Scripter
,