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.