Re: Factor

Factor: the language, the theory, and the practice.

Today In History

Wednesday, December 19, 2012

#wikipedia

For every day of the year, Wikipedia maintains a list of famous events, births, and deaths in history. For example, if you look at today in history, you will see that in 1843, Charles Dickens novel, A Christmas Carol first went on sale.

Wouldn’t it be great if you could use Factor to parse and display these famous historical events?

USING: accessors calendar formatting http.client io kernel
sequences xml xml.traversal ;

Using our calendar vocabulary, we will build a word that converts a timestamp into a Wikipedia URL:

: historical-url ( timestamp -- url )
    [ month-name ] [ day>> ] bi
    "https://en.wikipedia.org/wiki/%s_%s" sprintf ;

If you look at the source for these Wikipedia pages, you will find that it contains a series of unordered lists. In particular, we are interested in the second list containing “Events”. The third list contains “Births” and the fourth contains “Deaths”.

: historical-events ( timestamp -- events )
    historical-url http-get nip string>xml
    "ul" deep-tags-named second children-tags
    [ deep-children>string ] map ;

Sometimes it is a nice convention to build a word that produces output:

: historical-events. ( timestamp -- )
    historical-events [ print ] each ;

You can try this out:

IN: scratchpad today historical-events.
211 – Publius Septimius Geta, co-emperor of Rome, is lured
to come without his bodyguards to meet his brother Marcus
Aurelius Antoninus (Caracalla), to discuss a possible
reconciliation. When he arrives the Praetorian Guard murders
him and he dies in the arms of his mother Julia Domna.
324 – Licinius abdicates his position as Roman Emperor.
1154 – Henry II of England is crowned at Westminster Abbey.
1490 – Anne, Duchess of Brittany, is married to Maximilian I,
Holy Roman Emperor by proxy.
...

The code for this is on my GitHub, along with words to output historical births and deaths and formatted output that includes links to Wikipedia.