Expand Cut Tags

No cut tags

Date: 2008-03-10 01:03 pm (UTC)
ext_86356: (2632)
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.
(will be screened)
(will be screened if not validated)
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

If you are unable to use this captcha for any reason, please contact us by email at support@dreamwidth.org

May 2018

S M T W T F S
  12345
6789101112
13141516171819
20212223242526
27282930 31  

Most Popular Tags

Style Credit

Page generated Jul. 20th, 2025 07:20 pm
Powered by Dreamwidth Studios