fredag, november 28, 2008

The Erlang Rationale - The problem with ‘if’

Sigh. If was added as an almost “on the spur of the moment” hack. We knew how to compile guards and thought it might be useful in the case where you don’t have a value to match against. As Erlang has pattern matching we found that a “pure” if is used less than in many other languages, we never used it much ourselves and therefore didn’t really worry much about it. This is not really that strange as in many languages if is used in way which resembles very trivial pattern matching. For example in C:
if ((x = get_some_value()) != 0) {
    do stuff with x
else {
    do some other stuff
}
Also I don’t really have a problem using case when I want to do a conditional, but then again I am so used to it I don't think about it.

There have been repeated suggestions and discussions of either extending if to allow user defined boolean functions or adding a new construct. The problem with extending if is that the tests would no longer be guard tests and would handle differently for exceptions. A guard test silently just fails while a normal expression generates an error, which would make the change incompatible. We actually made cond a reserved word but never got around to adding it to the language.

6 kommentarer:

  1. In my opinion, if is the single worst construct in Erlang. There are so few places where it's needed though, that it's not a problem, really.

    Just my $0.02

    SvaraRadera
  2. I tend to agree with dmitrii. Even in my relatively limited experience with erlang case and head matching have taken a care of everything.

    SvaraRadera
  3. We/I added if because we occasionally got cases of the type

    case X of
    _ when X > 10 -> ...;
    _ when X > 0 -> ...;
    ...
    end,

    which look *really* terrible, even worse then if. I know you can break it out as a separate function but sometimes you just don't want to.

    With pattern matching I find that you very seldom need to use a traditional if.

    SvaraRadera
  4. Hello,

    Please add your site at http://www.sweebs.com. Sweebs.com is a place where other people can

    find you among the best sites on the internet!
    Its just started and we are collecting the best found on the net! We will be delighted to have

    you in the sweebs listings.

    Regards
    Kris

    SvaraRadera