[파일명: 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 다섯.
'프로그래밍 > OCaml' 카테고리의 다른 글
int 타입과 bigint 타입 간 상호 타입 변환 with OCaml (0) | 2013.02.03 |
---|---|
Pollard's rho method 소개: 정수의 인수분해(factorizing integers) with OCaml (0) | 2013.02.02 |
스트링 배열 정렬(sorting)하기 with OCaml (0) | 2013.02.02 |
손으로 계산하는 긴자리 곱셈표 만들기 with OCaml (0) | 2013.02.02 |
문자열 거꾸로 하기 with OCaml (0) | 2013.02.02 |