funcprog: Ocaml assignments from week 2

parent ad3fdcae
let isLeapYear x =
x >= 1582 && x mod 4 == 0 && (x mod 100 != 0 || x mod 400 == 0)
;;
let testLeapYear x =
Printf.printf "%4d: %b\n" x (isLeapYear x);;
(testLeapYear 1400);; (* false *)
(testLeapYear 1582);; (* false *)
(testLeapYear 1583);; (* false *)
(testLeapYear 1584);; (* true *)
(testLeapYear 1700);; (* false *)
(testLeapYear 2000);; (* true *)
exception Hell
let day_with_suffix day =
match day with
1 | 21 | 31 -> (string_of_int day) ^ "st"
| 2 | 22 -> (string_of_int day) ^ "nd"
| 3 | 23 -> (string_of_int day) ^ "rd"
| _ when day > 0 -> (string_of_int day) ^ "th"
| _ -> raise Hell
;;
let month_name month =
match month with
1 -> "January"
| 2 -> "February"
| 3 -> "March"
| 4 -> "April"
| 5 -> "May"
| 6 -> "June"
| 7 -> "July"
| 8 -> "August"
| 9 -> "September"
| 10 -> "October"
| 11 -> "November"
| 12 -> "December"
| _ -> raise Hell
;;
let date2str day month year =
Printf.sprintf "%s %s, %d" (month_name month) (day_with_suffix day) year
;;
(* correct date2str input: *)
print_string (date2str 2 2 2011);;
(* expected a raised Hell exception: *)
print_string (date2str (-2) 2 2011);;
let rec digitRoot number =
let result = ref 0 in
let current = ref number in (
Printf.printf "input: %d\n" !current;
while !current > 0 do
result := !result + (!current mod 10);
Printf.printf "%d + " (!current mod 10);
current := !current / 10;
done;
Printf.printf "= %d\n" !result;
if !result > 9 then
(digitRoot !result)
else
!result
)
;;
let test_digitRoot input =
print_string "--- test_digitRoot ---\n";
Printf.printf "%d -> %d\n" input (digitRoot input)
;;
(test_digitRoot 20);;
(test_digitRoot 24);;
(test_digitRoot 1234);;
(test_digitRoot 123456789);;
(test_digitRoot (-1));; (* what to do with negative numbers? *)
let even_len x =
if (x mod 2) == 0 then
x
else
x - 1
;;
let isPalindrome palin =
let result = ref true in (
for i = 0 to ((even_len (String.length palin)) / 2) - 1 do
if (palin.[i] != palin.[(even_len (String.length palin)) - i - 1]) then
begin
result := false;
end
else
()
done;
!result)
;;
Printf.printf "%b\n" (isPalindrome "asddsa")
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