Blog

About call-by-value, call-by-name and thunking

This is something nice I learned during the winter school in Marseille, and used right after it on a program I was implementing in OCaml. This week I finally got the time to write it down nicely with an example that hopefully makes things easier to understand =)

So in programming we often use some functions, right? These functions have arguments (which can be themselves functions). Call-by-value and call-by-name are two different strategies to deal with these arguments (and please do not confuse this with passing parameters as values and as references… these are actually two ways of passing parameters in the call-by-value paradigm, if I understand correctly). Here’s a brief explanation of both:

Call-by-value
The arguments of a function are evaluated and then their results are passed to the function.

Call-by-name
The arguments of a function are substituted directly on the function’s body and evaluated only when necessary.

Take, for example, the following function:

let f x = x +x

and apply it to (print “hi!!”; 4).
If  f (print “hi!!”; 4) is evaluated using a call-by-value strategy, the argument will be evaluated once, hi!! will be printed and the return value will be 8.
If  f (print “hi!!”; 4) is evaluated using a call-by-name strategy, the argument will be copied to the body of the function, which will become: (print “hi!!”; 4) + (print “hi!!”; 4). Then, each part of the sum will be evaluated, hi!! will be printed twice and the return value will be 8.

Now, as far as I know, most of the languages use the call-by-value strategy. Maybe because of efficiency, since the repeated use of an argument would cause it to be evaluated several times in the call-by-name strategy. But sometimes it is the case that we actually want a call-by-name strategy to be used. This happened to me when I was implementing a continuation passing style. Basically my function had two arguments, which were functions themselves, called success and fail. Some computation was done and depending on the result the function would be continued by success or fail. Now, I did not want these functions to be executed right away, of course, but only when I had already computed something and decided which was the case. This was implemented in OCaml, which uses the call-by-value strategy. So, in order to simulate a call-by-name, I had to use something called thunking.

Thunk
Thunks are types such as ()-> A which are used to delay evaluation, i.e., if a parameter of a function is of thunk type, it is not evaluated until needed, in a call-by-name style. Thunks simulate CBN in a CBV language.

This is easier to see with an example:

(* Quick OCaml example of call-by-value, call-by-name and thunking *)


let arg () = 
  print_endline “Function evaluated.”
;;


let cbv f =
  print_endline “=> Not using the argument, evaluated anyway.”
;;


let cbn f = 
  print_endline “=> Not using the argument, not evaluated.”
;;


let _ = 
  print_endline “Call-by-value:”;
  cbv (arg ());
  print_endline “Call-by-name:”;
  cbn (fun () -> arg ())
;;

You can try this by saving a file and executing it with ocaml. Cool, isn’t it?

Como mudar a política desse nosso país?

Taí uma iniciativa bacana: http://www.novo.org.br/

Achei muito sensatas as idéias deles e concordo com vários pontos de vista. Apesar de alguns críticos por aí falarem que isso é utópico, que não se faz política sem político, eu não acredito nisso. A minha opinião é que a gente precisa mesmo mudar de vez o jeito que política é feita nesse país. Vou mandar minha carta de apoio =)
Resumidamente, os principais pontos são:

  • Os cargos eletivos são oportunidades de prestação de serviço e não carreira profissional.
  • Todo gestor público ou privado deve trabalhar com metas.
  • É dever do partido dar suporte ao candidato antes e durante o mandato.
  • A reeleição consecutiva para cargos legislativos deve ser vetada.
  • A gestão eficiente resulta em melhores serviços e menos impostos.
  • A prestação de contas do Estado deve ser feita de forma transparente e acessível.
Mas além disso, eu vi alguns vídeos de palestras dos fundadores. Eles parecem ser pessoas sérias e competentes, que têm um discurso com conteúdo e princípios, diferente do que a gente vê por aí nos períodos de eleições.
Eu nunca tive muitas expectativas com a política no Brasil. Política não pode ser somente um jogo de interesses, de alianças e de troca de favores, e é isso que eu vejo desde que sou obrigada a votar. Campanhas ruins, de ataques ridículos ao adversário, promessas vazias que se repetem a cada 4 anos, um desespero de obter resultados e obras no ano da eleição… A política não devia ser movida a eleições, e sim a sociedade. Claro que todo candidato não é assim, mas os que não são, são exceções. Raríssimos, alías, e difíceis de encontrar. Todo mundo sabe como funciona a política no Brasil, e é frustrante. Eu anulei meu voto a maioria das vezes pra não ter que votar no “menor pior”. Acho isso um desaforo, e sempre fiquei pensando se tinha alguma coisa que eu poderia fazer pra melhorar.
Taí. Acho que essa pode ser uma boa maneira de começar. Pra essa campanha eu dou sim meu total apoio, e viro uma daquelas pessoas políticas chatas que vai tentar ficar te convencendo dessas idéias e princípios. Mas eu acho mesmo que não tem muito que convencer, a proposta fala por si só. E o que é bom, é bom sem precisar de propaganda, ou slogan, ou jingle.

Ah mon dieu… encore une fois!

I had to come to Marseille for this winter school, and since there were no direct flights, I took one with a connection in Paris. I got to Charles de Gaulle and quickly looked for the gate I had to board, it would start in 15 minutes. Then the boarding started, I entered the plane and sat at the last seat, by the window. I did not choose the seat, since I was alone, and this was assigned to me at check in. Everything was going well and I was looking at the people loading the airplane with luggages. Then I saw my bag, standing there right next to the thread mill that takes the bags inside. Suddenly the guys stopped loading and sat down on the cart. My bag was still there… One guy got up and scanned the barcode on it, he sat again. Then another guy scanned it. Still left it there. Then one guy got up, got my bag, put it on a cart and started driving away. I was watching everything from that little window, and I just wanted to shout “hey!! that’s my bag! come back here!”. But he would not listen, so I called the flight attendant, pointed out and said: “Do you see that red bag they are taking away? It’s mine!!”. The lady certainly did not see that coming. She started making phone calls, asked for my bag ticket and passport, talked to the pilot. But nothing helped… I could see my bag going away, but they could not find it and the plane had to leave. She apologized a hundred times, of course. How crazy is that? I actually saw what was going on and there was nothing anybody could do!! So after we landed she said I should go to the lost and found in Marseille so they could put my bag on the next flight.

As soon as I landed I went to the lost and found. The guy said that the bag was still in Paris and it should arrive in Marseille on the flight on 11 at night, or tomorrow morning. Really?? I knew that my bag was not arriving with me before leaving Paris! And he could not even assure me that it would arrive in Marseille the same day? What kind of logistics is that? He said the bag should get to the lost and found on Charles de Gaulle before being dispatched. Stupid protocols… making our lives harder.

I really don’t understand how these airline companies are able to control the flights’ times, organize a million airplanes on ground and on the sky and still loose baggages in stupid ways like that… Now I am in Marseille, with no clothes other that what I am wearing. Let’s just hope my bag makes the 11 pm flight.

Dog days are over

Just so I don’t lose the habit of posting songs. And to celebrate my very last course exam =D
Hopefully I won’t have to take courses again for a very very long time!!

News from Brazil

Yesterday at night we turned on the only channel from Brazil we have on TV to see some news. Here’s what we got:

– A guy reacts to a robbery, manages to immobilize the robber but then the robber’s friend comes and shoots the guy. In the middle of the street.
– A woman is stabbed to death on her own bed by the husband while the kids are hidden in the bathroom with the nanny. Hours latter, the husband is found dead, also stabbed, in a motel.
– A lady is killed in what seems to be a religious ritual and had her eyeballs and skin face removed.
– Police officers from Salvador are on strike and by now 78 people died, stores were robbed and buses were robbed, just because the police is not on the streets.

Really? I felt very bad hearing that… I don’t think I’ll watch the news ever again. It makes me sad that people do this kind of stuff, and afraid at the same time because of my family and friends in Brazil. Not that I’m not running risks here myself, but being killed because of a robbery is just ridiculous.

I started wondering several things. My first instinct was to really stop watching the news. I can get them on the internet every now and then, and if they continue to bother me, I can choose not to look at all. Then you’ll say that I am an alienated person, that I’m not up to date with what’s happening in the world. True. But do I really want to be up to date with those things? Sometimes ignorance is a blessing. I don’t think these news will add anything, except my lack of faith in humanity.

Then I thought what’s the good in putting such kind of news on TV. I mean, it’s worth maybe to know that the police is on strike, but a weird religious murder, a couple’s murder/suicide and cold blooded murder on the streets… why? Are they trying to alert us that there are crazy people out there? Or is this done just for the audience? I’m not sure what is the line between information and just gossip.

At last, as expected, I wondered why people do that stuff. Did this also happen centuries ago or is it something that emerged with our society? Is this part of human nature or was it developed with progress? I really have no idea… but I think that if we find the cause, it will be easier (or maybe not so hard) to make it better. More questions than answers at this point… if someone knows of literature on the subject, please let me know.

Return

The airport is quiet, people are talking on the streets and I don’t understand, there’s a guy (or girl) on the subway with really red hair, it’s snowing.

Yes, I’m definitely back in Vienna.

Banco do Brasil

It’s amazing to see how much trouble people put us through here is Brazil to try to guarantee our safety… The problem is that there’s always a smart ass trying to take advantage and steal money from other people, so the bank has to create a million traps for them. But as a result, people that have money at the bank also have to deviate from all the traps proving them to be themselves all the time in order to get their own money. It’s ridiculous…

Since I’ve moved to Austria, I’ve had all sorts of problems to access my online banking account. The problem is that every time I install some update on my computer, the bank’s certificate is somehow lost and I have to register my computer again to access my banking account. (Yes, in order to do some operations, such as bank transfers, I need to register the computer I’m using. Otherwise, I can only see the statement on the screen and nothing more). The problem is that every time I have to register the computer again, they do this by sending me a message on the mobile phone, or I have to personally go the bank. After I moved to Austria, my mobile in Brazil was cancelled, so the number they had there no longer existed. I asked if they could send the message to my father’s phone and they said I would have to go to the bank to register his phone on my account. How can this be more stupid?

Luckily, my father had a document giving him power to be me basically (I left it here signed before leaving Brazil, I knew it would be needed at some point). So with this letter he was able to go to the bank, register his phone. Then I entered the website, asked it to send the message to my father’s phone and he sent me an e-mail with the damn code. Now imagine that I would have to do this every time the browser is updated…

This happened once when he was visiting me in Vienna, i.e., his phone was there and not working. I used Skype to call the bank here and after a lot of waiting I talked to a lady asking here to authorize my computer and she said she could not do this because there was no way of proving that I was me. Really? She could ask me *anything* or *everything*, and I would answer correctly. But rules are rules, no matter how stupid they seem.

There is a branch of Banco do Brasil in Vienna and I tried going there to solve this problem. The lady was so rude and said that they could not help me at all. At the end, I have no clue what that branch is for… there is no cashier, no manager and they cannot do anything with respect to passwords…

Today the same thing happened after the latest update. Since I am in Brazil, I decided to call the bank to see if there’s an easier solution for that computer registering stuff. I knew that the phone password I had was canceled a long time for lack of use so I found another customer service number on the website and when I call it, guess what? There’s no solution… simple as this.

At the end, I don’t blame them, but all these people that force them to do this for our “safety”.

About being together

This year lots of my friends are getting married. But I know a few of them that actually ended their engagement. I was talking to my boyfriend about this the other day, and I was trying to understand what drives a person to end such a commitment. To him, the answer is simple, one of the two simply did not want to get married anymore. Either they found out that they did not love the other, or they had so many questions or just stopped loving each other. And then he asked me: “Are you sure that you will *always* be in love with me?”. I replied: “Of course not. The fact that we are in love know does not imply that we will always feel like this”. I thought this was a sad but true truth… And it got me thinking about marriage and long term relationships.

I thought of all the couples I know that are married for decades. Does the fact that they did not get a divorce imply that they have always been in love with each other? Not likely… Every couple I know enough has gone through some rough times. Sometimes they get over it, sometimes they break up. So what is it that determines if two people should be together? What is it that makes some people stay with each other although they have times doubting their love?

The answer could be a million things… and I suspect that if I ask around lots of couples married for 50 years they will all have different answers. Of course I could go on saying that is a matter of trade off, that the more two people are committed, the harder is for them to break up… but this is not a business. And these are hardly measurable things… Instead of trying to find a formula, I started to think on what holds people together through hard times. Maybe this is different for each person, but for me, it’s the memories. They give me hope that things will get better because they have been better before. I like to think why and when we fell in love. I remember the warm feeling, the butterflies in the stomach, the late night conversations… I remember the first time I noticed the things I like most about him. These thoughts make me feel good, and I realize the hard times cannot overcome all the happiness we had and will have. I hope I can always feel like this =)

PS: I wonder how much in love people that have been together for a long time feel about each other… It would be a shame to find out that this feeling goes away.