Challenge #228 [Easy] Letters in Alphabetical Order
So from here on out, I'm going to try and keep up with /r/dailyprogrammer and do the challenges (, and post solutions and explanations), in order to document my progress and increase my ability to communicate via writing.
Here is the code I submitted.
open Batteries let test = ["billowy"; "biopsy"; "chinos"; "defaced"; "chintz"; "sponged"; "bijoux"; "abhors"; "fiddle"; "begins"; "chimps"; "wronged"] let check (str:string) = let word = String.to_list str in let sorted = List.sort Char.compare word in let reved = List.rev word in if sorted = word then str ^ " IN ORDER\n" else if sorted = reved then str ^ " REVERSED ORDER\n" else str ^ " NOT IN ORDER\n";; List.map print_string (List.map check test)
The logic behind it is: there is a function
check that checks if a word is in
order or not (or reversed). It sorts the word (by character) and makes a reverse
copy of it, then compares them. Note that
= was used instead of
==. Then I
mapped it through the list, and printed them out one by one. The difficulty here
for me was to convert a
string into a
char list, which wasn't support in
core OCaml (which confuses me, because the majority of other languages support
After a bit of googling, I found that the
Batteries library has that function,
so off I went!