Higher Order Select in Ruby
Higher Order Select in Ruby
When I was converting my blog to jekyll, I had to write a nested select in Ruby and found it to be a little painful.
In Ruby:
# For a given feed, return all the entries that
# are blog posts rather than templates, etc.
def posts(feed)
# The post must have a category of type #post
feed.entries.select do |entry|
!entry.categories.select do |c|
c.term == 'http://schemas.google.com/blogger/2008/kind#post'
end.empty?
end
end
In Scala, things are a little simpler thanks to anaphora: the ability to easily reference earlier state implicitly. That’s what the _ means in this context.
feed.entries.filter(!_.categories.filter(_.term == "http://schemas.google.com/blogger/2008/kind#post").isEmpty)
Imagine the following sentence in English: “Steve used Steve’s keys to start Steve’s car”. Most programming languages insist on that level of verbosity.
Raganwald has a nice piece exploring Anaphora in Ruby.
# San Francisco — 13 December, 2009