Datasheet
778
Running with the Dynamic Language Runtime
def main
Array.new(11) { gets.to_i }.reverse.each do |x|
y = f(x)
puts “#{x} #{(y>400) ? ‘TOO LARGE’ : y}”
end
end
end
This isn’t a Ruby book, and that fact isn’t lost on me. Nonetheless, this is the
best dynamic language that I can use for an example — bar none.
Two functions are defined: f and main. Main accepts 11 numbers from the
console and then moves them to an integer array (that’s what gets.to_i
does). For each value in the array, it sets y equal to f(x) and then sees if it
is higher than our arbitrary value. If so, it prints “TOO LARGE”; otherwise, it
prints the number.
Why is being dynamic important for this algorithm? It isn’t. You could do it
all statically typed. The dynamic bit does have an impact, though.
First, f(x) doesn’t care what x is. The program assumes that whatever
comes in gets changed to an integer at gets.to_i, but the function itself
is case agnostic. This is good and bad, because if we do happen to give it a
string or some other type, it will fail.
The array itself isn’t typed, either. This can have benefits, because it is pos-
sible to drop a differently typed value in there if you know you are just going
to write it to the screen.
Dynamic C#
Of course, C# now has similar features, right? We should be able to do the
same thing! Yes, in fact, we can. Here’s the code:
static dynamic f(dynamic x)
{
return (Math.Sqrt(x) + 5.0 * Math.Pow(x, 3.0));
}
static void Main(string[] args)
{
dynamic[] array = new Array[11];
for (int i = 0; i < 11; i++)
{
array[i] = Console.ReadLine();
}
for (int i = 10; i>=0; i--)
{
53_563489-bk08ch01.indd 77853_563489-bk08ch01.indd 778 3/19/10 8:17 PM3/19/10 8:17 PM