I love functional programming…

Today I wrote the following code:

def _query_helper(x,y):
  return lambda(v): x(v) and not v.startswith(y)
query = reduce(_query_helper,['http://','mailto:'],lambda(v):v!=None)

I’m using this with the Beautiful Soup XML/HTML parser to filter the list of link targets found in a document:

soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
dests = soup.findAll('a',href=query)

I couldn’t really think of a way to do this neatly without using a functional style. I’m pretty pleased with this. When learning this kind of thing at University I was somewhat sceptical how useful it would be. I was wrong. Thank you Larry!

Leave a Reply

Your email address will not be published. Required fields are marked *