Code can be found here: https://raw.github.com/louis1204/ocaml_training/master/pa1review.ml
(* returns the sum of a list *)
let rec sumList list = match list with
[] -> 0
| head::tail -> head + sumList tail;;
Pretty straight forward.
(* returns the digits of an int *)
let rec digitsOfInt num =
if num < 10
then [num]
else
digitsOfInt(num/10) @ [num mod 10];;
This was also pretty straight forward. A refresher to me was the use of @ to concat two lists.
(* additive persistence. # of sums of digits until 1 digit *)
let additivePersistence num =
let count = 0 in
let rec breakdown(n, counter) =
if n > 9 then
breakdown(sumList(digitsOfInt(n)), (counter+1))
else
counter
in
breakdown(num, count);;
This was a bit challenger and I had to look at my previous answer. I was having trouble coming with a solution to have a counter.
In the end we define a count in the scope of additivePersistence to handle the counting, then the recursive function, breakdown
to continually breakdown the number.
(* digital root. the resulting number from additive persistence *)
let digitalRoot num =
let count = 0 in
let rec breakdown(n, counter) =
if n > 9 then
breakdown(sumList(digitsOfInt(n)), (counter+1))
else
n
in
breakdown(num, count);;
Pretty much the same.
(* listReverse *)
let rec listReverse list = match list with
[] -> []
| head::tail -> listReverse(tail)@[head];;
(*explode*)
let explode s =
let rec _exp i =
if i >= String.length s then [] else (s.[i])::(_exp (i+1)) in
_exp 0;;
(*palindrome*)
let palindrome string =
if listReverse(explode(string)) = explode(string) then true
else false;;
No comments:
Post a Comment