August 23, 2015

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.

Original link

Here is the code I submitted.

open Batteries

let test = ["billowy";

let check (str:string) =
    let word = String.to_list str in
    let sorted = List.sort 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";; print_string ( 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 this).

After a bit of googling, I found that the Batteries library has that function, so off I went!

Tags: ocaml easy challenge