15

If a language is type-safe does that mean one could automatically assume that its statically typed since you would have to check types at compile time ?

2 Answers2

15

C, for example, is statically typed and not type safe, while Haskell is statically typed and type safe. Most (all?) dynamically typed languages are type safe, as they have means of checking types at runtime to make sure they're the right thing. Additionally, these languages assume that because you have chosen to incur the performance penalty of including runtime type information, you would want to use that information as effectively as possible, and so generally do not allow interpreting a chunk of memory as the wrong type.

Dynamically typed languages have an additional measure of type safety, which is coercion. For example, if you type [] + [] in javascript, it will see that the operands to + are arrays and cannot be added directly, and so will convert them both to strings, giving the result of "" (the empty string).

Some languages, like javascript, will usually coerce other things to strings, while PHP for example will coerce strings to numbers to compare them.

EDIT: Type safety means not being allowed to interpret a chunk of memory holding something of type A as something of type B. As an example of type unsafety, C++ has the reinterpret_cast operator, which means "convert anything to anything else even if it doesn't make sense to do so." For example,

float a = 6.2;
int b = reinterpret_cast<int>(a);
//b now contains some form of garbage

For a much more complete explanation of type safety, see this answer.

Community
  • 1
  • 1
Dan
  • 12,409
  • 3
  • 50
  • 87
  • thanks for replying, i have a question though. If you are only doing type checking at runtime (dynamic languages), how can they be type safe ? Maybe i have the wrong definition of type safe, would you be able to elaborate on your answer a little? –  Nov 12 '12 at 14:45
1

I would hesitate to call a dynamic-typed language type-safe, however rigorously it checks types at runtime, because runtime might be too late to do anything about the error!

You could justifiably call such a language strongly typed, but I wouldn't call it type-safe.

Catching the error at compile time gives you a chance to fix it...

For a good example of a type safe language, look at SPARK.

In SPARK, indexing off the end of an array is a type error (each array has a new type for its index, and you have a value that isn't compatible with that type)

You would normally prove there are no such errors before even compiling the program...