lunes, 10 de agosto de 2015

LED is my new Hello World - Mercury Time

This one was a little bit tricky and longer than I expected...it also...forced me to spend a lot of time reading the documentation as there aren't many tutorials or books about Mercury...

Anyway...in the end it's working fine, so I'm quite happy -:)

Mercury has a lot of pretty convenient functions...you just need to find them out -;)

led_numbers.m
:- module led_numbers.
:- interface.
:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module list, string, int, array, char.

:- pred get_leds(list.list(character)::in, list.list(character)::in, 
                 int::in, list.list(string)::out ) is det.
 
get_leds(LDIGITS, LDIGITS_AUX, N, RESPONSE) :-
 (
  LEDS = array([array([" _  ","| | ","|_| "]),
                array(["  ","| ","| "]),
                array([" _  "," _| ","|_  "]),
                array(["_  ","_| ","_| "]),
                array(["    ","|_| ","  | "]),
                array([" _  ","|_  "," _| "]),
                array([" _  ","|_  ","|_| "]),
                array(["_   "," |  "," |  "]),
                array([" _  ","|_| ","|_| "]),
                array([" _  ","|_| "," _| "])
               ]),
  list.length(LDIGITS,LEN),
  ( if LEN > 0 then
   HEAD = det_head(LDIGITS),
   TAIL = det_tail(LDIGITS),
   char.to_int(HEAD, HEAD_I:int),
   HEAD_N:int = HEAD_I - 48,
   LINE = elem(HEAD_N, LEDS),
   SUB_LINE = elem(N, LINE),
   get_leds(TAIL, LDIGITS_AUX, N, RESULT),
   RESPONSE = [SUB_LINE] ++ RESULT
    else if N < 2 then
   get_leds(LDIGITS_AUX, LDIGITS_AUX, N+1, RESULT),
   RESPONSE = ["\n"]  ++ RESULT
    else if N = 2 then
   RESPONSE = ["\n"]
    else
   RESPONSE = [] )
 ). 
 
main(!IO) :-
 io.write_string("Enter a number: ",!IO),
 io.read_line_as_string(Result, !IO),
 ( if
   Result = ok(String),
   NUM = string.strip(String),
   to_char_list(NUM,LDIGITS),
   get_leds(LDIGITS, LDIGITS, 0, RESPONSE)
  then
   io.write_string(string.join_list("", RESPONSE), !IO)
  else
   io.write_string("Not a number...",!IO)
 ).


Anyway...here are the screens -;)



Hope you like it -;)

Greetings,

Blag.
Development Culture.

miércoles, 5 de agosto de 2015

My first post on Mercury

So...my new language for a couple of weeks...is Mercury -:)

You may ask...what is Mercury?

Mercury looks like Prolog, but feels like strict Haskell or pure OCaml.
 In other words is a logical, functional and object-oriented programming language...

As always...I needed to develop an app to learn how to use it...and while it gave me more than one headache...here it is -;)

fibo.m
:- module fibo.
:- interface.
:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module string, int.

:- pred fibo(int::in, int::in, int::in, string::out) is det.

fibo(NUM, A, B, FIBS) :-
 ( 
  if A = 0 
  then fibo(NUM-1,A+B,B,FIB), FIBS = int_to_string(A) ++ " " ++ int_to_string(B) ++ 
                                     " " ++ int_to_string(A+B) ++ " " ++ FIB
  else if A > 0, NUM > 1
  then fibo(NUM-1,A+B,A,FIB), FIBS = int_to_string(A+B) ++ " " ++ FIB
  else FIBS = ""
 ).
 
main(!IO) :-
 io.write_string("Enter a number: ",!IO),
 io.read_line_as_string(Result, !IO),
 ( if
   Result = ok(String),
   string.to_int(string.strip(String), N)
  then
   fibo(N,0,1,FIBS),
   io.write_string(FIBS,!IO)
  else
   io.write_string("Not a number...",!IO)
 ).

The cool thing about Mercury is that it forces you to not allow your app to fail...as the "else" is mandatory...if you enter a number then it's fine...but if you enter a letter, you are forced to do something...

Here are the pics...



 Now...I just need to break my head a little bit more trying to make my LED_Numbers app -:D

Greetings,

Blag.
Development Culture.

viernes, 31 de julio de 2015

LED is my new Hello World - Zonnon Time

You knew this was coming...don't you? -;)

So here...I took another approach because Zonnon doesn't have a built-in split command...and also because I'm not sure how to create an array of arrays and because I couldn't make my procedure return an array and then assign it to another array -:(

Still...I'm quite happy with the result -:D

LED_Numbers.znn
module LED_Numbers;

var num, text, concat:string;
var leds:array 10 of string;
var led:array 3 of string;
var i, j, z, len, lenled:integer; 

begin
 leds[0]:=" _  ,| | ,|_| ,";
 leds[1]:="  ,| ,| ,";
 leds[2]:=" _  , _| ,|_  ,";
 leds[3]:="_  ,_| ,_| ,";
 leds[4]:="    ,|_| ,  | ,";
 leds[5]:=" _  ,|_  , _| ,";
 leds[6]:=" _  ,|_  ,|_| ,";
 leds[7]:="_   , |  , |  ,";
 leds[8]:=" _  ,|_| ,|_| ,";
 leds[9]:=" _  ,|_| , _| ,";
 write("Enter a number: ");readln(num);
 len:=num.Length;
 for j:=0 to len - 1 do
  i:=0;
  text:=leds[integer(num[j])-48];
  lenled:=text.Length;
  for z:= 0 to lenled - 1 do
   if text[z] # "," then
    concat:= concat + string(text[z]);
   else
    led[i]:=led[i] + concat;
    concat:="";
    i:= i + 1;
   end;
  end;
 end; 
 writeln(led[0]);
 writeln(led[1]);
 writeln(led[2]);
end LED_Numbers.

Anyway...here are the pictures -;)



Greetings,

Blag.
Development Culture.

My first post on Zonnon

As always...I was looking for new and cool programming languages to learn...and then Mark Teichmann came up with something really nice -;) The Zonnon programming language...

So...what's Zonnon? Zonnon is a general-purpose programming language in the Pascal, Modula-2 and Oberon family...and it's run on .NET/Mono...

It's been a really long time since I used Pascal or Delphi...but...just like riding a bicycle...the knowledge came back as soon I started writing some code -;)

Now...the only problem I have with Zonnon...is that's there's almost no documentation...and what's available is in Russian...so...a lot Google helped me up...


Here's the Fibonacci Numbers app...


Fibo.znn
module Fibo;
var num: integer;
var a, b: integer;

procedure fib (var num, a, b : integer): string;
var result: string;
var ab: integer;
begin
 result := "";
 if (a > 0) & (num > 1) then
  num := num - 1;
  ab := a + b;
  result := result + string(ab) + " " + fib(num, ab, a);
 elsif a == 0 then
  num := num - 1;
  ab := a + b;
  result := string(a) + " " + string(b) + " " + string(ab) + " " + fib(num, ab, b);
 end;
 return result;
end fib;

begin
 a := 0;
 b := 1;
 write("Enter a number: ");readln(num);
 writeln(fib(num,a,b));
 writeln("");
end Fibo.

And a couple of pictures...




I need to keep playing and exploring Zonnon...there's a lot of cool things still hiding from me -;)

Greetings,

Blag.
Development Culture.

jueves, 23 de julio de 2015

LED is my new Hello World - Forth Time

Just as you expected...it's time again for my LED Numbers application...this time...using Forth -:)

The code is a little bit longer that I would have expected...but I guess it's either because I'm still a Forth newbie...or because Forth being a stack based programming language has it's own way of dealing with this kind of application...

Here's the source code...enjoy! -;)

LED_Numbers.fth
VARIABLE picky

: COLLECT_PICKY DUP 1- picky ! ;

: NPICK COLLECT_PICKY 2 * 0 ?DO picky @ PICK LOOP ;

: SPLIT BEGIN DUP WHILE 10 /MOD REPEAT DROP DEPTH ;

: First_Line
  CASE
  0 OF SPACE ." _  " ENDOF 1 OF SPACE SPACE ENDOF
  2 OF SPACE ." _  " ENDOF 3 OF ." _  " ENDOF
  4 OF SPACE SPACE SPACE SPACE ENDOF 5 OF SPACE ." _  " ENDOF
  6 OF SPACE ." _  "ENDOF 7 OF ." _   "  ENDOF 
  8 OF SPACE ." _  " ENDOF 9 OF SPACE ." _  " ENDOF
  ENDCASE ;
  
: Second_Line
  CASE
  0 OF ." | | " ENDOF 1 OF ." | " ENDOF
  2 OF SPACE ." _| " ENDOF 3 OF ." _| " ENDOF
  4 OF ." |_| " ENDOF 5 OF ." |_  " ENDOF
  6 OF ." |_  "ENDOF 7 OF SPACE ." |  "  ENDOF 
  8 OF ." |_| " ENDOF 9 OF ." |_| " ENDOF
  ENDCASE ;
  
: Third_Line
  CASE
  0 OF ." |_| " ENDOF 1 OF ." | " ENDOF
  2 OF ." |_  " ENDOF 3 OF ." _| " ENDOF
  4 OF SPACE SPACE ." | " ENDOF 5 OF SPACE ." _| " ENDOF
  6 OF ." |_| "ENDOF 7 OF SPACE ." |  "  ENDOF 
  8 OF ." |_| " ENDOF 9 OF SPACE ." _| " ENDOF
  ENDCASE ;

: LED 
  SPLIT
  NPICK
  DEPTH 3 / 0 ?DO First_Line LOOP CR
  DEPTH 2 / 0 ?DO Second_Line LOOP CR
  DEPTH 0 ?DO Third_Line LOOP ;

And of course...you want to see an image...so here it goes -;)


Hope you like it... -:D

Greetings,

Blag.
Development Culture.

martes, 21 de julio de 2015

My first post on Forth

So...after a very long time...I finally decided to learn Forth...and if I thought I have dealt with difficult programming languages before...I was like Jon Snow...I knew nothing -:(

Forth is a stack based programming language...meaning that you program using a stack with the LIFO functionality...Last In - First Out...

Something like this...you enter 1 2 3 and Forth will output it as 3 2 1...weird, huh?

Of course...I started to read a book...and unlike most other times...I have finish it a long time ago...but with Forth...one book is not just enough...I have been reading and coding like crazy...

The book is Starting Forth by Leo Brodie...


The book itself is really good...it's 166 pages so it's not very long and gives you a nice introduction to the world of Forth...of course...as I said...one book is not enough...and even when this book is really good and highly recommended...Forth is very difficult to grasp but learning it is just amazing -:)

It took me a very long time but finally I was able to come with an example of my already "famous" Fibonacci Numbers...

Fibo.fth
: FIBO 
   1 SWAP 
   0 DUP . 
   ?DO 
      DUP . OVER OVER + ROT DROP 
   LOOP 
   DROP DEPTH 
   DEPTH 2 = IF 2DROP 0 THEN 
;

I told you...Forth is not by any chance and easy language...and actually I wrote the code in just one line...but put it here in different lines to make more clear...

Let's see an image...


I'm sure I going to spend quite more time with Forth...as I feel that's there so much to learn...if you like what you see...learn it too -;) Otherwise...look for something less weird -:)

BTW...I'm using pForth...I used gForth when I first started but I think pForth is more Forth complaint...

Greetings,

Blag.
Development Culture.

lunes, 29 de junio de 2015

Exploring SparkR

A colleague from work, asked me to investigate about Spark and R. So the most obvious thing to was to investigate about SparkR -;)

I installed Scala, Hadoop, Spark and SparkR...not sure Hadoop is needed for this...but I wanted to have the full picture -:)

Anyway...I came across a piece of code that reads lines from a file and count how many lines have a "a" and how many lines have a "b"...

For this code I used the lyrics of Girls Not Grey by AFI...

SparkR.R
library(SparkR)

start.time <- Sys.time()
sc <- sparkR.init(master="local")
logFile <- "/home/blag/R_Codes/Girls_Not_Grey"
logData <- SparkR:::textFile(sc, logFile)
numAs <- count(SparkR:::filterRDD(logData, function(s) { grepl("a", s) }))
numBs <- count(SparkR:::filterRDD(logData, function(s) { grepl("b", s) }))
paste("Lines with a: ", numAs, ", Lines with b: ", numBs, sep="")
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken



0.3167355 seconds...pretty fast...I wonder how regular R will behave?

PlainR.R
library("stringr")

start.time <- Sys.time()
logFile <- "/home/blag/R_Codes/Girls_Not_Grey"
logfile<-read.table(logFile,header = F, fill = T)
logfile<-apply(logfile[,], 1, function(x) paste(x, collapse=" "))
df<-data.frame(lines=logfile)
a<-sum(apply(df,1,function(x) grepl("a",x)))
b<-sum(apply(df,1,function(x) grepl("b",x)))
paste("Lines with a: ", a, ", Lines with b: ", b, sep="")
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken


Nice...0.01522398 seconds...wait...what? Isn't Spark supposed to be pretty fast? Well...I remembered that I read somewhere that Spark shines with big files...

Well...I prepared a file with 5 columns and 1 million records...let's see how that goes...

SparkR.R
library(SparkR)

start.time <- Sys.time()
sc <- sparkR.init(master="local")
logFile <- "/home/blag/R_Codes/Doc_Header.csv"
logData <- SparkR:::textFile(sc, logFile)
numAs <- count(SparkR:::filterRDD(logData, function(s) { grepl("a", s) }))
numBs <- count(SparkR:::filterRDD(logData, function(s) { grepl("b", s) }))
paste("Lines with a: ", numAs, ", Lines with b: ", numBs, sep="")
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken



26.45734 seconds for a million records? Nice job -:) Let's see if plain R wins again...

PlainR.R
library("stringr")

start.time <- Sys.time()
logFile <- "/home/blag/R_Codes/Doc_Header.csv"
logfile<-read.csv(logFile,header = F)
logfile<-apply(logfile[,], 1, function(x) paste(x, collapse=" "))
df<-data.frame(lines=logfile)
a<-sum(apply(df,1,function(x) grepl("a",x)))
b<-sum(apply(df,1,function(x) grepl("b",x)))
paste("Lines with a: ", a, ", Lines with b: ", b, sep="")
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken


48.31641 seconds? Look like Spark was almost twice as fast this time...and this is a pretty simple example...I'm sure that when complexity arises...the gap is even bigger...

And sure...I know that a lot of people can take my plain R code and make it even faster than Spark...but...this is my blog...not theirs -;)

I will come back as soon as I learn more about SparkR -:D

UPDATE

So...I got a couple of comments claiming that read.csv() is too slow...and I should measuring the process not the loading of an csv file...while I don't agree...because everything is included in the process...I did something as simple as moving the start.time after the csv file is done...let's see how much of a change this brings...

SparkR

Around 1 second faster...which means that reading the csv was really efficient...


Plain R

Around 6 seconds faster...read.csv is not that good...but...SparkR is almost 50% faster...

HOLLY CRAP UPDATE!

 Markus from Spain gave me this code on the comments...I just added a couple of things to make complaint...but...damn...I wish I could code like that in R! -:D Thanks Markus!!!

Markus's code
logFile <- "/home/blag/R_Codes/Doc_Header.csv"
lines <- readLines(logFile)
start.time <- Sys.time()
a<-sum(grepl("a", lines, fixed=TRUE))
b<-sum(grepl("b", lines, fixed=TRUE))
paste("Lines with a: ", a, ", Lines with b: ", b, sep="")
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken


Simply...superb! -:)

Greetings,

Blag.
Development Culture.

jueves, 18 de junio de 2015

LED is my new Hello World - Lua Time

Getting on with my tradition of building an LED application for each and every new programming language that I learn...it's time for Lua -;)

LedNumbers.lua
local function split(s,delim)
 local result = {}
 for match in (s..delim):gmatch("(.-)"..delim) do
  table.insert(result,match)
 end
 return result
end

leds = {[0] = " _  ,| | ,|_| ",
        [1] = "  ,| ,| ",
        [2] = " _  , _| ,|_  ",
        [3] = "_  ,_| ,_| ",
        [4] = "    ,|_| ,  | ",
        [5] = " _  ,|_  , _| ",
        [6] = " _  ,|_  ,|_| ",
        [7] = "_   , |  , |  ",
        [8] = " _  ,|_| ,|_| ",
        [9] = " _  ,|_| , _| "}

io.write("Enter a number: ")
num = io.read()
for i = 1,3 do
 for j = 1, #num do
  line=split(leds[tonumber(string.sub(num,j,j))],",")
  io.write(line[i])
 end
 print("")
end

What you can see right away...and that's something that really surprised me...is that Lua doesn't provide a "split" or "explode" command out of the box, so you need to make it yourself...actually...the same holds true for Haskell...but for me...functional languages are on another league...and anyway...Haskell's implementation of the split function is way shorter...

Here's the result...


Greetings,

Blag.
Development Culture.

viernes, 12 de junio de 2015

My first post on Lua

Lua is a programming language that always intrigued me but that I never spend time on trying to learn...

This has changed of course -;) As I have start reading Beginning Lua Programming...


So...what is Lua exactly? Well...it's is a powerful, fast, lightweight, embeddable scripting language.

A simple description for a simple language...and nope...I'm not implying simple as "useless" but rather as simple on its learning curve and its design...Lua is indeed pretty powerful and you will be more than surprised if you know where its being used...just search and get amazed -;)

The syntax pretty much reminds me of Python or Julia...so it's fairly easy to get used to it...

As an example...here is my Fibonacci numbers example...

Fibonacci.lua
function fib(num,a,b)
 local result = ""
 if a > 0 and num > 1 then
  result = result .. (a+b) .. " " .. fib(num-1,a+b,a)
 elseif a == 0 then
  result = a .. " " .. b .. " " .. (a+b) .. " " .. fib(num-1,a+b,b)
 end
 return result
end

io.write("Enter a number: ")
num = tonumber(io.read())
print(fib(num,0,1))


Here's a couple of tests -:)



Greetings,

Blag.
Development Culture.

LED is my new Hello World - OpenEuphoria Time

I started using OpenEuphoria a long time ago...when it was called RapidEuphoria...but...I stopped using as I started learning other languages...

Yesterday...all of a sudden...I realized that it is indeed a really cool language, so I wanted to refresh myself and what better than building my LED example one more time -;)

So...here it is -:)

LedNumbers.ex
include get.e
include std/map.e
include std/convert.e
include std/sequence.e

sequence num
sequence snum
object onum
atom anum
map leds = new()
   put(leds, 0, {" _  ","| | ","|_| "})
   put(leds, 1, {"  ","| ","| "})
   put(leds, 2, {" _  "," _| ","|_  "})
   put(leds, 3, {"_  ","_| ","_| "})
   put(leds, 4, {"    ","|_| ","  | "})
   put(leds, 5, {" _  ","|_  "," _| "})
   put(leds, 6, {" _  ","|_  ","|_| "})
   put(leds, 7, {"_   "," |  "," |  "})
   put(leds, 8, {" _  ","|_| ","|_| "})
   put(leds, 9, {" _  ","|_| "," _| "})
   
num = prompt_string("Enter a number: ")
snum = breakup(num,1)
for i = 1 to 3 do
        for j = 1 to length(num) do
            anum = to_number(snum[j])
            onum = map:get(leds,anum)
            puts(1,onum[i])
        end for
        puts(1,"\n")
end for
puts(1,"\n")

Of course...you want to see it in action -:D


If you haven't already...give OpenEuphoria a try...it's really fun -;)

Greetings,

Blag.
Development Culture.