funcprog: Finished week 2, assignment 5.4.

parent 0b3c4094
let even_len x = #load "str.cma";;
if (x mod 2) == 0 then
x
else
x - 1
;;
let isPalindrome palin = (*
let result = ref true in ( * The function isPalindrome checks if a given character string is a palindrome,
for i = 0 to ((even_len (String.length palin)) / 2) - 1 do * i.e. it is identical whether being read from left to right or from right to
if (palin.[i] != palin.[(even_len (String.length palin)) - i - 1]) then * left. Note that this function removes punctuation and word dividers before
begin * checking the given character string.
result := false; *)
end let isPalindrome raw =
else (*
() * Check if the left and right character of the string are the same. An
done; * empty string and a string with length 1 is by definition a palindrome.
!result) * Check uses a character string `s' and its length `l' to recursively
;; * determine if `s' is a palindrome.
*)
let rec check s l =
l < 2 || (s.[0] == s.[l-1] && (check (String.sub s 1 (l-2)) (l-2)))
in
(* Remove punctuation / word dividers -> only alphanumeric chars remain. *)
let filter = Str.regexp "[^a-zA-Z0-9]+" in
let filtered = String.lowercase (Str.global_replace filter "" raw) in
(check filtered (String.length filtered))
;;
Printf.printf "%b\n" (isPalindrome "asddsa") let test_isPalindrome str =
Printf.printf "isPalindrome(\"%s\") -> %b\n" str (isPalindrome str)
;;
test_isPalindrome "";;
test_isPalindrome "a";;
test_isPalindrome "baas saab";;
test_isPalindrome "never odd or even";;
test_isPalindrome "Was it a rat i saw?";;
test_isPalindrome "expected failure!";;
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment