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…
I’m not even sure what a monad is, but I still write code like this from time to time…
$A(ul.getElementsByTagName('input')).map(Element.extend).findAll(function(input) {return input.type == 'radio';}).each(function(radio) {
radio.disable();
radio.checked = false;
});
Yes, that’s javascript.
Trent Bartlem
2 Jul 08 at 5:21 pm
Trent, have you tried to understand what a monad is? Are there specific areas you need help with?
Tony Morris
2 Jul 08 at 7:38 pm
My degree is in hardware and low-level computer systems so my knowledge of CS Theory is incomplete. I can barely read most of your blog posts, for instance. Daniel’s comment on your latest entry was more approachable, though vague.
From what I understand, a monad is a function that returns (result or side-effect) instead of just a result. The analogy I use is a Java method where the return value also incorporates all exceptions that CAN be thrown from the method (or parameters), whether they were actually thrown or not.
This implies correlation between knowledge of monads and the shift to using unchecked exceptions in Java although I’m unable to articulate exactly why. I guess that’s just my level of understanding; I get why things are neat, am uncertain on the application, and unable to grasp the wider implications.
Trent Bartlem
3 Jul 08 at 9:37 am
[...] recorded first by theescapist on 2008-07-20→ Nobody *ever* uses map, et. al… (example 1) [...]
Recent URLs tagged Hpricot - Urlrecorder
23 Jul 08 at 4:15 pm