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

let is_member arr s = List.exists (fun x -> x = s) arr ;;

let findIndex s data =
    let rec loop s1 l acc =
        match l with
        | x::xs -> if x = s1 then acc else loop s1 xs (acc + 1)
        | [] -> -1
    in
        let k = loop s data 0 in
        k ;;

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 words = ["하나"; "둘"; "셋"; "넷"; "다섯"; "여섯"] in

printf "list: " ;
printList words ;
printf "\n"  ;
let three = "셋" in
let check = is_member words three in
printf "Is %s a membert of list? %s\n" three (string_of_bool check) ;
if check then begin
    let where1 = findIndex three words in
    printf "%s has been found at index %d.\n" three where1 ;
    if where1 < ((List.length words) - 1) then
        printf "The next word of %s is %s.\n" three (List.nth words (where1 + 1)) ;
end ;

print_newline() ;

printf "Sorting...\n" ;
let otherwords = List.sort String.compare words in
printf "sorted list: " ;
printList otherwords ;
printf "\n"  ;
let check = is_member otherwords three in
printf "Is %s a membert of sorted list? %s\n" three (string_of_bool check) ;
if check then begin
    let where1 = findIndex three otherwords in
    printf "%s has been found at index %d.\n" three where1 ;
    if where1 < ((List.length otherwords) - 1) then
        printf "The next word of %s is %s.\n" three (List.nth words (where1 + 1)) ;
end ;

------------------------------------------------


실행> ocaml testStringFindInList.ml
list: [하나, 둘, 셋, 넷, 다섯, 여섯]
Is 셋 a membert of list? true
셋 has been found at index 2.
The next word of 셋 is 넷.

Sorting...
sorted list: [넷, 다섯, 둘, 셋, 여섯, 하나]
Is 셋 a membert of sorted list? true
셋 has been found at index 3.
The next word of 셋 is 다섯.


Posted by Scripter
,