Is the ability to pass a function/reference to a function a desirable trait?
Oh golly yes. For a functional language it's really a requirement. It lets you do things like:
case user_prefs("sort-by")
when "name":
radix_func = lambda { |a,b| a.name <=> b.name }
when "dob":
radix_func = lambda { |a,b| a.dob <=> b.dob }
when "hair-color":
radix_func = lambda { |a,b| a.haircolor <=> b.haircolor }
end
sorted_people = people.sort_by &radix_func
When your language makes a function a first-class object (a quantity that you can assign to variables or store in data structures the same way you would any other quantity like a string or an integer), this kind of idiom quickly becomes very natural. I'm not sure I'd say that Ruby is "a functional language" but it certainly inherits enough functional traits (like functions as first-class objects and a "lambda" function which is used to create them) to feel like one.
You're right that doing this in C is a good way to make your application blow up, but that's partly because the way you implement this in C is with pointers to functions, which gives the compiler no good way to check the type or number of arguments you're passing to your dereferenced functions, so it kind of has to say "I hope in hell you know what you're doing", close its eyes and jump. A decent dynamically typed language doesn't suffer from those shortcomings and makes it a lot easier to build code like this.
no subject
Date: 2008-03-10 01:03 pm (UTC)Oh golly yes. For a functional language it's really a requirement. It lets you do things like:
When your language makes a function a first-class object (a quantity that you can assign to variables or store in data structures the same way you would any other quantity like a string or an integer), this kind of idiom quickly becomes very natural. I'm not sure I'd say that Ruby is "a functional language" but it certainly inherits enough functional traits (like functions as first-class objects and a "lambda" function which is used to create them) to feel like one.
You're right that doing this in C is a good way to make your application blow up, but that's partly because the way you implement this in C is with pointers to functions, which gives the compiler no good way to check the type or number of arguments you're passing to your dereferenced functions, so it kind of has to say "I hope in hell you know what you're doing", close its eyes and jump. A decent dynamically typed language doesn't suffer from those shortcomings and makes it a lot easier to build code like this.