[erlang-questions] OO programming style in Erlang?

Richard A. O'Keefe ok@REDACTED
Tue Jan 23 23:44:02 CET 2007

Ladislav Lenart <lenartlad@REDACTED> wrote:
	Let's suppose I have to write a lot of code like this
	in Smalltalk:
	   anObject isNil
	     ifFalse: [anObject doSomething].
	I can "extend the language" by providing a new method
	which takes a block of code as its only argument:
	   Object>>ifNotNilDo: oneArgBlock
	     "This is the branch where object (self in this
	      context) is not nil and so the block is evaluated
	      (with the object as its argument)."
	     ^oneArgBlock value: self.
	   UndefinedObject>>ifNotNilDo: oneArgBlock
	    "This is the branch where object (self in this
	     context) is actually nil and so the block is ignored
	     and nil is returned."
PLEASE don't do that.  #ifNil: #ifNotNil: #ifNil:ifNotNil: and
#ifNotNil:ifNil: exist in more than one version of Smalltalk and
there is no point in being incompatible with them.

	Now I can replace the code above with shorter and more
	readable form:
	   anObject ifNotNilDo: [:obj | obj doSomething].
Or, in some existing Smalltalks:

    anObject ifNotNil: [anObject doSomething]

And in Erlang you can write
    case X of [] -> do something ; _ -> do something else end

You have missed out one important step.
The usual Smalltalk syntax for conditionals and loops *does* make
use of blocks (= anonymous functions = Erlang 'fun' expressions),
*but* those blocks are actually compiled in line.  If you want that
to happen, you *also* have to patch the Smalltalk compiler.  (Which,
given that Smalltalk provides compiler sources, is not entirely out
of the question.  But it's harder than it looks.)

Erlang has several extension facilities:
    - the C-wannabe preprocessor
    - parse transforms
    - hacking the (open source) compiler
but none of them is quite as convenient as Lisp macros or Scheme hygienic
macros and the syntax of Erlang has much to do with that.  However, the
conventional infix operators in Erlang syntax have, I suspect, had much
to do with Erlang's acceptance.

More information about the erlang-questions mailing list