Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Every if and every switch should be viewed as a lost opportunity for dynamic polymorphism.

The truly sad thing about OOP is people not embracing the duality between if-statement dispatching (pattern matching) and oop-style dynamic dispatching.

In situations where you have a fixed set of types its better to use switch statements and even in other cases, sometimes its better to still use if statements to avoid scatering your code all over the place (specially if you compiler warns you if you forget to handle on of the cases when updating things)

http://www.c2.com/cgi/wiki?ExpressionProblem



if-statement dispatching is not pattern matching.

Pattern matching yields more type information than if statements and can match recursively on multiple arguments (which even multi-method dynamic dispatch cannot). However, it always dispatches on a closed sum type, whereas OOP-style dynamic dispatch is on an open sum type, so the mechanisms are useful in different circumstances.


Can you expand on this difference?


"If/switch" branching is sometimes called "boolean blindness":

http://existentialtype.wordpress.com/2011/03/15/boolean-blin...

The reason is that no new type information is gained when you branch.

When you pattern match, however, you gain new names in scope that have new types. This is new type information such that the branch choice represents new information not only in the program position, but also at the type level.

For example:

  if(x != NULL) {
     .. compiler does not know if x is null or not ..
  } else {
     .. ditto
  }
Whereas with pattern matching:

  case x of
    Nothing -> .. Scope gets no new value.
                  x is a Maybe type, not usable as a direct value
    Just y -> .. Scope gets "y" as a value of the type
                 inside the maybe, which is directly usable.
Also, you can define a function like:

  f (Just (Right x)) (y:ys) = ...
  f (Just (Left e)) [] = ...
  f _ xs = ...
which pattern-matches multiple arguments at the same time, including recursive pattern matching (Right inside Just, Left inside Just, etc).

If you meant the difference regarding open/closed sum types, I can expand on that.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: