Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to perform compile time type-check in Ruby?

I know Ruby is dynamically and strongly typed, but AFAIK, current syntax doesn't allow checking the type of arguments at compile time due to lack of explicit type notation (or contract) for each argument.

If I want to perform compile-time type check, what (practically matured) options do I have?

Update

What I mean type-check is something like typical statically typed language. Such as C. For example, C function denotes type of each argument and compiler checks passing-in argument is correct or not.

void func1(struct AAA aaa)
{
    struct BBB bbb;
    func1(bbb);  // Wrong type. Compile time error.
}

As an another example, Objective-C does that by putting explicit type information.

- (id)method1:(AAA*)aaa
{
    BBB* bbb = [[AAA alloc] init];  // Though we actually use correctly typed object...
    [self method1:bbb];             // Compile time warning or error due to type contract mismatch.
}

I want something like that.

Update 2

Also, I mean compile-time = before running the script. I don't have better word to describe it…

like image 515
eonil Avatar asked Jan 19 '14 01:01

eonil


People also ask

Does Ruby have type checking?

Ruby itself is a dynamically type-checked language and follows a "duck typing" approach: If it walks like a duck and it quacks like a duck, then it must be a duck. What this means is that Ruby developers generally don't worry too much about an object's type, but whether it responds to certain "messages" (or methods).

Does Ruby have compile time?

The important thing to remember about Ruby is that there isn't a big difference between ``compile time'' and ``runtime. '' It's all the same. You can add code to a running process. You can redefine methods on the fly, change their scope from public to private , and so on.

Does Ruby have type inference?

In particular, we use type inference to model most of Ruby's idioms as precisely as possible without any need for programmer intervention. For example, we track the types of local variables flow-sensitively through the program, e.g., allowing a variable to first contain a String and then later an Array.


1 Answers

There was a project for developing a type system, a type inferencer, a type checker and a syntax for type annotations for (a subset of) Ruby, called Diamondback Ruby. It was abandoned 4 years ago, you can find its source on GitHub.

But, basically, that language would no longer be Ruby. If static types are so important to you, you should probably just use a statically typed language such as Haskell, Scala, ML, Agda, Coq, ATS etc. That's what they're here for, after all.

like image 115
Jörg W Mittag Avatar answered Sep 28 '22 08:09

Jörg W Mittag