Archive for the ‘hof’ tag
Nobody *ever* uses map, et. al… (example 1)
Inspired by Daniel’s comment on Tony’s blog, I figured I’d start documenting the times I use “functional” constructs in my everyday work.
Consider this piece of XML, returned from an external web service:
<suggestions>
<suggestion>
<suggestion>paddington, NSW</suggestion>
<location>true</location>
</suggestion>
<suggestion>
<suggestion>paddington, QLD</suggestion>
<location>true</location>
</suggestion>
</suggestions>
Perform the following:
- Parse out each suggestion, turn it into an instance of
Suggestion; - Capitalise the first letter;
- Sort by name;
- Remove duplicates;
Here’s some Ruby code that does this, parsing by Hpricot:
class SuggestionsParser
def self.parse(node)
suggestions = node.search("//suggestions/suggestion").map do |s|
Suggestion.new(s.at("suggestion").inner_text.capitalise_first_letter, s.at("location").inner_text == "true")
end
suggestions.sort.uniq
end
end
But of course nobody ever does this…