Erlang Type System

Ulf Wiger ulf@REDACTED
Sat Sep 17 20:30:58 CEST 2005


Den 2005-09-17 17:36:50 skrev <orbitz@REDACTED>:

> I was hoping someone could clear up some confusion.  As I understand it,  
> with a dynamically typed language you can change the type of x.  For  
> instance in Python x = 1; x = 1.5;  Obviously we can't do that in Erlang.

Dynamically typed rather means that the type of
an object is determined at runtime, instead of
at compile time.

For example, the compiler will not have any
complaints about this code:

foo() ->
   X = {a,b,c},
   [H|T] = X.

but if you run it, it will cause a run-time error,
since the head-tail pattern cannot be used on a tuple.

In a statically typed language, this program wouldn't
compile.

(Now, the compiler could very well complain about this,
and perhaps hipe actually does. I know dialyzer would,
but it would still be a warning, since it's a valid
program in a statically typed language.)

> So is that a proper idea of what dynamic typing is, and
> does this make Erlang statically typed or dynamically?

I think the term you're after is "single assignment", which
means that variables can only be bound once. This really
doesn't have anything to do with static vs dynamic typing.
Most functional languages use single assignment at the core
(I believe that with Haskell MVars, for example, you can
have global mutable variables.)

There is another expression, "strongly typed", which means
that the type system cannot be subverted. For example,
the above program might work if the language allowed a
tuple to be treated as a list when needed. But this is
not done in Erlang. Instead, you must explicitly convert
 from one type to another (e.g. [H|T] = tuple_to_list(X))
Compare this to C, for example, which allows you to
re-cast a variable as something else, doing integer
arithmetic on pointers, etc.


> Most people tell me Erlang is still dynamically typed
> because the variable passed in a function can be of any
> type.

Yes, but whether the function accepts the argument
passed is up to the program, and is determined at
run-time. This is exactly what dynamic typing is about.

While my example was a program that compiles but doesn't
work, one can write programs in a dynamically typed
language that would be nearly impossible, or at least
very difficult, to type in a statically typed language
... unless you resort to giving everything the any()
type, of course, but that kind of defeats the purpose
of static type checking.

/Uffe
-- 
Ulf Wiger



More information about the erlang-questions mailing list