Re: Factor

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

Wolfram|Alpha using Factor

Thursday, January 27, 2011

#networking

Wolfram|Alpha is a fun and useful “calculation engine” from the creators of Mathematica. Launched in mid-2009, it is available on the web, mobile devices, and from search engines. Last week, Wolfram announced version 2.0 of their API. As part of that announcement, they made it “free” for up to 2,000 non-commercial requests per month.

Since Factor has a visual REPL, I thought it would make a perfect client for Wolfram|Alpha. Starting today, you can do this:

The Wolfram|Alpha API website has both an API reference and an API explorer that can help you learn how it works. To get started, you need to sign up to receive an API ID.

USING: accessors formatting http http.client images.gif
images.http io kernel namespaces sequences splitting
urls.encoding xml xml.data xml.traversal ;

We will store the API ID in a symbol, that you can set:

SYMBOL: wolfram-api-id

The API is queried by creating URLs (from the query input and API ID) and parsing the response as XML.

: query ( query -- xml )
    url-encode wolfram-api-id get-global
    "https://api.wolframalpha.com/v2/query?input=%s&appid=%s"
    sprintf http-get nip string>xml ;

Inside the XML response are “pods” corresponding to the different types of information returned by Wolfram|Alpha. You can choose to receive the “pods” as plaintext, images, sounds, HTML, or Mathematica values. By default, the API returns plaintext and images.

We can create a wolfram-image. word that queries the API, extracts the “pods”, outputs the title and images contained in each “pod”:

: wolfram-image. ( query -- )
    query "pod" tags-named [
        [ "title" attr print ]
        [
            "img" deep-tags-named
            [ "src" attr http-image. ] each
        ] bi
    ] each ;

Thats how to integrate with Wolfram|Alpha. Before using, remember to set your API ID:

IN: scratchpad "XXXXXX-XXXXXXXXXX" wolfram-api-id set-global

In addition to this, I made some minor style improvements (the gray titles and indentation in the screenshot), created a wolfram-text. word that prints the response as plaintext, and a wolfram. word that detects if you are running Factor on the command-line or the graphic interface and outputs text or images appropriately.

You can find the code on my GitHub.

Note: I also needed to make a few minor fixes to Factor’s libraries to get this to work. They are not yet merged into the main Factor repository, but should be soon: