Imperative in python
Functional on a object oriented flavor in ruby

Note: You can do the opposite, ruby in imperative and python in functional (I’m guessing on the python part, but it’s probably true)

# choose all values from a list that are not in a matrix

# imperative in python
res = []

for value in list:
  present = False
  for mlist in matrix:
    if value in mlist:
      present = True
      break
   if not present:
     res.append(value)
# functional in ruby
res = list.select { |value| !matrix.flatten.member? value }

# restrict the matrix to values in list

# imperative strikes back
res = []

for mlist in matrix:
  current_mlist = mlist[:]
  for mvalue in mlist:
    if mvalue not in list:
      current_mlist.remove(mvalue)
  res.append(current_mlist)
# functional responds
res = matrix.map do |mlist|
  mlist.select { |mvalue| list.member? mvalue }
end

Requiem for a Dream

April 27, 2008

Vieram-me perguntar de onde tinha tirado a foto do meu perfil do last-fm.

A resposta é simples. De um dos mais brilhantes filmes que já vi. Se gostas de cinema e ainda não viste, este é para ti. (Para ver e rever)

Cartaz do Enterro da Gata 2008

Enterro da Gata 2008

Dia 10 – Jorge Palma, Gabriel o Pensador – 9 euros estudante / 12 não estudantes
Dia 11 – Linda Martini, James – 9 estudante / 12 não estudantes
Dia 12 – Rita Redshoes, David Fonseca – 8 euros estudante / 11 não estudantes
Dia 13 – Mind da Gap, Irmãos Verdades – 8 euros estudante / 11 não estudantes
Dia 14 – Neurónios Abariados, Quim Barreiros – 9 estudante / 12 não estudantes
Dia 15 – Banda Vencedora do UMplugged, Xutos e Pontapés – 9 estudante / 12 não estudantes

Camionetas UM -> Gatódromo

Polo Azurém: Ida entre 22h e a 1h. Volta entre as 4h e as 6h30

Polo Gualtar: Ida entra 21h30 e as 2h. Volta entre as 3h e as 6h30

Vemo-nos lá?

( Provavelmente pela última vez. )

Acabadinho de vir da garantia, onde passou um mês para trocarem a board sem que tenham conseguido resolver nenhum dos outros problemas que indiquei.

Olhem para a bateria e digam-me se isto é normal:

The mona Lisa

Está mesmo a sair o novo Ubuntu.

Enquanto não sai – e antecipando os habituais problemas de uma estreia, ou seja, servidores atulhados – deixo uma palavra amiga a apontar para o mirror de Software Livre do Centro ao Apoio ao Open-Source que vai ter os CD’s disponiveis para download em:

PS. Já lá esta o release candidate.

links for 2008-04-22

April 22, 2008

Simple sorting.

First comes a demonstration of the most common error :P
Then a simple sort
After that comes a first sort_by
And then a complete sort_by (sorted first by fname and then by lname).

>> h = [{'fname' => 'Nuno', 'lname' => 'Job'},
  {'fname' => 'Nuno', 'lname' => 'Fonseca'},
  {'fname' => 'Catarina', 'lname' => 'Pinto'},
  {'fname' => 'Nuno', 'lname' => 'Pinto'},
  {'fname' => 'Nuno', 'lname' => 'Antunes'}
]
>> h.sort
NoMethodError: undefined method '< =>' for
{"lname"=>"Job", "fname"=>"Nuno"}:Hash
from (irb):35:in `sort'
from (irb):35
from :0
>> h.sort{|a,b| a['fname'] < => b['fname']}
=> [{"lname"=>"Pinto", "fname"=>"Catarina"},
{"lname"=>"Job", "fname"=>"Nuno"},
{"lname"=>"Fonseca", "fname"=>"Nuno"},
{"lname"=>"Pinto", "fname"=>"Nuno"},
{"lname"=>"Antunes", "fname"=>"Nuno"}]
>> h.sort_by{|p| p['fname']}
=> [{"lname"=>"Pinto", "fname"=>"Catarina"},
{"lname"=>"Job", "fname"=>"Nuno"},
{"lname"=>"Fonseca", "fname"=>"Nuno"},
{"lname"=>"Pinto", "fname"=>"Nuno"},
{"lname"=>"Antunes", "fname"=>"Nuno"}]
>> h.sort_by{|p| [p['fname'], p['lname']]}
=> [{"lname"=>"Pinto", "fname"=>"Catarina"},
{"lname"=>"Antunes", "fname"=>"Nuno"},
{"lname"=>"Fonseca", "fname"=>"Nuno"},
{"lname"=>"Job", "fname"=>"Nuno"},
{"lname"=>"Pinto", "fname"=>"Nuno"}]

Bob Dylan em Portugal

April 16, 2008

E eu na Dinamarca.

Resumo: A preservação da privacidade entre várias bases de dados apresenta-se como um dos mais intrigantes desafios na criptografia actual. Várias técnicas têm sido desenvolvidas no sentido de tentar resolver este problema. Este artigo surge então como uma revisão bibliográfica sobre o tema com especial foco na Anonymization, Private Information Retrieval e Secure Multi-Party Computation. Serão também apresentadas algumas directrizes para trabalho futuro, no qual se tentará aplicar os conhecimentos adquiridos a um problema concreto.

Link: report.pdf

Haskell $

April 14, 2008

Note: I know you will look away as soon as you see f x. Please don’t. You can see some interesting things in this post.

I was on the train with João and I was delighted to see my old friend $. I also miss composite (.) but $ is really the coolest shortcut Haskell gives a developer. So what is $?

It’s defined as:

f ($) x = f x

What does it does?

Prelude> let f x = map (succ) $ filter ( < 5 ) x
Prelude> f [4,5,7]
[5]
Prelude> let f  = zipWith ($)
Prelude> f [succ,id] [5,4]
[6,4]

Ulisses gave me the weird example. The first one was created by myself. In the first one we filter a list for numbers that are inferior to five and then we apply succ function to it. That is, we add one. :P Without $ we would have

Prelude> let f x = map (succ) (filter ( < 5 ) x)
Prelude> f [4,5,7]
[5]

So we got the parenthesis off and that always great to help make the code more readable. At least I simply love this symbol. Ulisses sample is quite more complex. First off all because it is in point-free/point-less notation. zipWith is a function that receives two lists and applies then function provided pair by pair. Like if I want to add [1,2,3] and [3,2,1] I can:

Prelude> zipWith (+) [1,2,3] [3,2,1]
[4,4,4]

Ain’t it cool? So in this function we simply apply function that goes in the first list (id and succ) to the numbers in the second. Looks easy like this doesn’t it? ;) If it doesn’t just to read it and digest it and you’ll figure it out easily.

Let code the same samples in Ruby. Unfortunately zipWith (should I commit it? :P) doesn’t exist in ruby I’ll have to work with another sample using plain zip (it’s the same as zipWith (\a b -> [a]++[b])).

irb(main):001:0> [1,2,3].zip([3,2,1])
=> [[1, 3], [2, 2], [3, 1]]

Well ruby handles this pretty well without $. We just need to do:

irb(main):002:0> [1,2,3].zip [3,2,1]

Because it’s object oriented this kind of issues don’t exist in Ruby. There are no expressions with large number of parenthesis as well. despite this I must agree that the Haskell version is far more readable than the ruby one:

irb(main):003:0> [4,5,7].select {
  |i| i < 5
}.map { |i| i.succ }
=> [5]

But I still miss $.I miss coding in Haskell. It’s just plain fun.

I hope that I have helped you see why languages like Haskell and Scheme do matter, and others like Python and Ruby can be both useful and fun to work with!

Site do dia

April 14, 2008

dscape@dscape:~$ history | awk '{print $2}' \
| sort | uniq -c | sort -rn | head
86 sudo
45 cd
27 ll
23 ./script/server
21 rm
17 ls
12 vim
7 startx
5 glxinfo
4 su

Worst movie ever.

A frase é do Lars Gustafsson, no meu livro favorito “A morte de um Apicultor”. Que com um pouco de sorte o João Moura anda a ler.