jueves, 19 de marzo de 2015

Real World OCaml - Book Review

I finally finished reading the Real World OCaml book...and I really enjoyed it -:)


This book, just like all the "Real World" series gives you a deep introduction into the language and allow you to start coding pretty fast...of course...if you have used any Functional programming language before...that really helps and OCaml has of course some aspects that makes it not so easy to learn...


The more you read this book, the more you're going to like OCaml...it's a really nice language -:)

The book covers the basics like Lists and Patterns, Records, Variants and Error-Handling.  But of course it goes beyond with Functors, Objects and Command-Line Parsing...not letting important concepts like JSON handling Concurrent Programming aside. So...it's a pretty complete reference to start out.

By the way...the book is 509 pages...so it's pretty long...but full of examples and demonstrations...

Here's a little code that I wrote to flat out lists -;)

Flat_List.ml
open Core.Std

let rec flat list =
 match list with
  | [] -> ""
  | head :: tail -> head ^ (flat tail)

let () = 
 printf "%s" (flat ["1";"2";"3"])

Here's the result...


As you can see...OCaml is fun...so go ahead...read this book and expand your knowledge -;)

Greetings,

Blag.
Development Culture.

lunes, 2 de marzo de 2015

LED is my new Hello World - OCaml Time

Learning OCaml is not easy...I have to admit that...but I'm moving forward -;) So, here's my take on LED Numbers...

LED_Numbers.ml
open Core.Std

let get_leds number =
let leds = [0, [" _  ";"| | ";"|_| "];
            1, ["  ";"| ";"| "];
            2, [" _  ";" _| ";"|_  "];
            3, ["_  ";"_| ";"_| "];
            4, ["    ";"|_| ";"  | "];
            5, [" _  ";"|_  ";" _| "];
            6, [" _  ";"|_  ";"|_| "];
            7, ["_   ";" |  ";" |  "];
            8, [" _  ";"|_| ";"|_| "];
            9, [" _  ";"|_| ";" _| "]] in
 for i = 0 to 2 do
  for j = 0 to String.length(number) - 1 do
   let line = List.Assoc.find_exn leds 
        (int_of_string(Char.to_string(number.[j]))) in
   printf "%s" (List.nth_exn line i)
  done;
  print_string "\n"
 done
 
let () =
 print_string "Enter a number: "
 let num = read_line() in
 get_leds num

The funny thing is that at first I tried to translate my previous Julia and Go codes...but then I remembered that even when OCaml can be made into some sort of an imperative language...it's actually Functional in its core...so I said...Ok...I need to reuse my Haskell code...but somehow I start thinking about a new whole different way of doing it...and I think I came out with a more cleaner and well done version...which is something that only learning a new programming language can give you...a new way of thinking about old problems -;)

Here are the screenshots as always -:)



Greetings,

Blag.
Development Culture.