miércoles, 28 de enero de 2009

Net simulator toy problem in Io

Another little test in Io language.

Packets are generated in a node with a content and a destination. Nodes are linked in a ring and passOn packages unless the package is for themselves.

Next versions to come, with subclassed nodes and more tests.

Syntax highlighted version in http://pastie.org/373095

Packet := Object clone do(
content := nil
destinatary := nil
)

Node := Object clone do (
id ::= nil
next ::= nil
generate := method(content, dest,
a := Packet clone
a content = content
a destinatary = dest
#a destinatary println
passOn(a)
)

receive := method(packet,
("I'm ".. self id .. ". The packet goes to".. packet destinatary .. "") println
if(packet destinatary == self id,
("I've received a package with the message:".. packet content .. "") println ,
#if (packet content asString containsSeq("sleep") and self id == 4, wait(2)) #nonblocking? anyone?
passOn(packet)))

passOn := method(packet,
#self id asString println
if(self next != nil, r:= self next receive(packet), "WTF?! I've no next node!" println))
)

lista := List clone
lista append (Node clone do (setId(0)))

for(i,100,1,-1,
lista append(Node clone do(setId(i) setNext(lista at(lista size -1)))))

lista at(0) next = lista at(lista size-1)
l1 := lista at(0) generate("matat1",45)
#l2 := lista at(0) generate("matatsleep",65)
#l3 := lista at(0) generate("matat3",20)
Future Work is Handling packages in a thread (and learning how to use futures), to be able to block some packages in certain nodes but be able to continue passing nodes along while processing (blocking) a given package.

That would allow having many packages navigating the 'net'.

miércoles, 21 de enero de 2009

a couple of perl gotchas

Yesterday I spent long time trying to catch 2 bugs in my code. It's not that perl is bad documented but me keeping forgetting things, so I'll put how did I solve them.

First one: perlvar are GLOBAL

Being used to use $_, you always find it has the correct value, so rarely localize it (only in nested loops for me). But I was setting $/ line separator to paragraph mode ($/="";) in a function, and though when I exited that block it would be set to the $/ value of returning blog.

FALSE: you should localize $/ in order not to interfere other parts of the module, nor other modules using $/.

local $/="";


Other one is looks_like_number from Scalar::Util.

I was using the flip-flop operator in scalar constant, and somewhat remembered something of returning an 'E' on the last line that matched. I used looks_like_number to check that, but.. omg! "23E0" looks like a number! It makes sense, but I didn't thought of it at first.

while(<>){
  $range = /foo/ .. /bar/;
  if(looks_like_number($range) && $range !~ /E/ && $range>2 ){
   #do things
   }
}

jueves, 25 de diciembre de 2008

Io language, a consistent scripting language

Some days ago I discovered a new language called Io (that's capital 'i' and 'o'). It's inspired by smalltalk, but with few features of other languages like self, lisp or lua. FYI, I discovered it among other cool languages. There are even more esoteric languages here.

First thing to say about Io is it's minimalist. Really minimalist. Only look at it's site to see it. As a minimalist language, its doc is also minimalist, so you have to understand the little doc fully, and I mean *really* understand. Io is a Prototype-based language with a syntax similar to smalltalk, but more minimal (assignation is a message too). Its introspection is astonishing aswell, and it introduces a concept of context which I'm still not very confortable with.

Anyway, I've already written my first program (a typical guessing number game) for Io. Here's the code.

guesser := Object clone
guesser toGuess := Random value(100) ceil
file := File standardInput
guess := file readLine asNumber
while(guess != guesser toGuess,
   if(guess < guesser toGuess,
     "higher" println,
     "lower" println)
   guess = file readLine asNumber
)
"ok, el numero es " print
guesser toGuess println


Ah! comunity is very friendly and willing to help (you can find them at #io @freenode

jueves, 4 de diciembre de 2008

sbbuilder is out

Bien. He hecho mi primera aplicación oficial para vector linux ( http://www.vectorlinux.com )

Es un programa para generar SlackBuilds con la estructura correcta para añadirlo en los repos sin dificultad.

Link al anuncio.

Disfruten de la simplicidad de perl + Template Toolkit para hacer algo util en apenas 40 lineas

miércoles, 3 de diciembre de 2008

Popen en squeak. pipe entre el proceso externo y el caller

En un post anterior me preguntaba como capturar la info de un comando que tiramos al sistema. Pues bien, la solucion es sencilla.

Abrir el universe package browser e instalar 2 paquetes: OSProcess y commandShell (los 2 estan en Tools IIRC). Las ultimas versiones, por favor :)

Bien, pues una vez tenemos los paquetes instalados (con sus deps), solo tenemos que ejecutar

salida := (PipeableOSProcess command: 'ls') output .

Ahi lo tenemos. Sencillo, eh?

Saludos

En http://wiki.squeak.org/squeak/572 encontre la solucion.

lunes, 1 de diciembre de 2008

modifying constructors

En smalltalk es una práctica común (por lo que he visto) hacer muchas funciones para crear un objeto determinado, es decir, hacer una creadora enganchada a uno o varios setters.

De un objeto paquete, podriamos tener las siguientes creadoras:

new
createWithContent:
createWithContent:andDestination:

Bien, como bien sabemos, todo es un objeto y todo eso... y cuando decimos todo es TODO. las instancias son objetos, las funciones son objetos, las clases son objetos... y claro, si las clases son objetos, la particularidad que tienen es que son capaces de crear otros objetos (las simples instancias no pueden).

Para hacer nuevas constructoras de clase, debemos modificar la clase, o sea pinchar en 'Class', y definir la nueva funcion ahi.

createWithContent: aString
|temp|
temp := self new.
temp content: aString.
^temp.

De esta forma, hemos creado una nueva funcion constructora, que aprovecha el viaje para setear un valor.

Si analizamos lo que hace es bien sencillo. simplemente notar que self new se refiere a Paquete new , o sea, la creadora que hubieramos llamado si no tuvieramos el parametro extra. new es un metodo que implementan las Clases, no las instancias.

Log donde aprendí esto (en català) : http://raimonster.googlepages.com/smalltalk3_new_initialize.txt .

Gracias a Gerard por la ayuda.

miércoles, 26 de noviembre de 2008

Domingos

Hay domingos que molan muuuuuuuucho.
Aquellos de sofa y tele y esperar que pasen las horas, y mirar alrededor, y decir: "Joer, que bien que estoy, aunque mañana vuelva a ser un dia de mierda"