wtd
|
Posted: Wed May 18, 2005 4:33 pm Post subject: Native List/Array Syntax Support |
|
|
Let the arguments begin!
How valuable is it to a language to have native syntactic support for lists or arrays?
Let's consider an example: Let's say I want to be able to pass an arbitrary number of options to a function. Now, I don't want arguments for each of those options, or a function call would be absurdly complicated. I also don't want to use a variable number of arguments, since that can be a mess to implement.
I can use bitwise math. So, let's look at a function called "my_print". It takes a string to print, and a number of options. "INDENT" means add a tab at the beginning of the string. "CAPITALIZE" means capitalize the first letter. "END_LINE" means skip to a newline when we're done.
Now, if we make each of these constants in the program, each with unique values that are powers of 2, we know that any particular combination will yield a unique value.
code: | INDENT = 1
CAPITALIZE = 2
END_LINE = 4
def my_print(str, options)
case options
when 1
str = "\t" + str
when 2
str.capitalize!
when 3
str = "\t" + str
str.capitalize!
when 4
str += "\n" unless str =~ /\n$/
when 5
str = "\t" + str
str += "\n" unless str =~ /\n$/
when 6
str.capitalize!
str += "\n" unless str =~ /\n$/
when 7
str = "\t" + str
str.capitalize!
str += "\n" unless str =~ /\n$/
end
print str
end |
Noe I can call this like so:
code: | my_print("hello", CAPITALIZE | END_LINE) |
Or:
code: | my_print("hello", CAPITALIZE + END_LINE) |
But that implementation is just nasty and filled with repeated work, and even if I factored those out into functions it would look nasty.
So, what's the option. Well, let's consider the possibility of just sending the function an array of strings (or symbols, in Ruby) representing the various options.
code: | def my_print(str, options)
str.capitalize! if options.include? :capitalize
str = "\t" + str if options.include? :indent
str += "\n" if options.include? :end_line and str !~ /\n$/
print str
end |
Now everything is neatly defined in the function itself. Changing external constants around won't change the behavior of the function. The implementation itself becomes more natural. There's no repeated work.
Calling the function:
code: | my_print("hello", [:capitalize, :end_line]) |
Of course, Ruby offers even more support for arrays with the slurpy operator that takes any extra arguments and puts them into an array, so...
code: | def my_print(str, *options)
str.capitalize! if options.include? :capitalize
str = "\t" + str if options.include? :indent
str += "\n" if options.include? :end_line and str !~ /\n$/
print str
end
my_print("hello", :capitalize, :end_line) |
So... as I said folks, have at it. Is such syntax a huge advantage for languages possessing it, or just unnecessary syntactic clutter and a potential source of massive memory consumption? |
|
|