|
|
|
|
|
by eco
3945 days ago
|
|
Yeah, it's a lot like lisp in that regard. I'm glad I learned D even though I don't use it professionally if only because it changed the way I look at some things. The algorithm chaining enabled by UFCS and the range based standard library can lead to some very beautiful code (at least as far as C-family languages go). It also made me painfully aware of how often I copy strings in C++ (string_view cannot come soon enough). Here's a snippet of code I hacked together in D for a bot to scrape titles from pages of urls in irc messages. matchAll(message, re_url)
.map!( match => match.captures[0] )
.map!( url => getFirst4k(url).ifThrown([]) )
.map!( content => matchFirst(cast(char[])content, re_title) )
.cache // cache to prevent multiple evaluations of preceding
.filter!( capture => !capture.empty )
.map!( capture => capture[1].idup.entitiesToUnicode )
.map!( uni_title => uni_title.replaceAll(re_ws, " ") )
.array
.ifThrown([]);
It uses D's fast compile-time regex engine to look for URLs, then it downloads the first 4k (or substitutes an empty array if there was an exception), uses regex again to look for a title, filters out any that didn't find a title, converts all the html entities to their unicode equivalents (another function I wrote), replaces excessive whitespace using regex, then returns all the titles it found (or an empty array if there was an exception). There's stuff to improve upon but compared to how I would approach it in C++ it's much nicer. |
|