Programming Languages – Why Math.Sqrt() is Static

api-designhistorylanguage-designmathprogramming-languages

In a discussion about static and instance methods, I always think, that Sqrt() should be a instance method of number types instead of a static method. Why is that? It obviously works on a value.

 // looks wrong to me
 var y = Math.Sqrt(x);
 // looks better to me
 var y = x.Sqrt();

Value types obviously can have instance methods, as in many languages, there is an instance method ToString().

To answer some questions from the comments: Why should 1.Sqrt() not be legal? 1.ToString() is.

Some languages do not allow to have methods on value types, but some languages can. I am talking about these, including Java, ECMAScript, C# and Python (with __str__(self)defined). The same applies to other functions like ceil(), floor() etc.

Best Answer

It is entirely a choice of language design. It also depends on the underlying implementation of primitive types, and performance considerations due to that.

.NET has just one static Math.Sqrt method that acts on a double and returns a double. Anything else you pass to it must be cast or promoted to a double.

double sqrt2 = Math.Sqrt(2d);

On the other hand, you have Rust which exposes these operations as functions on the types:

let sqrt2 = 2.0f32.sqrt();
let higher = 2.0f32.max(3.0f32);

But Rust also has universal function call syntax (someone mentioned that earlier), so you can choose whatever you like.

let sqrt2 = f32::sqrt(2.0f32);
let higher = f32::max(2.0f32, 3.0f32);