Monday, December 25, 2006

On second thought...

Actually, Google sucks. Yahoo is much better. It offers unlimited use of its REST API, which is so simple, I was able to whip up a search thing in 20 minutes:

USING: http.client xml xml.utilities kernel sequences
namespaces http math.parser help ;
IN: yahoo

TUPLE: result title url summary ;

C: <result> result

: parse-yahoo ( xml -- seq )
"Result" tags-named* [
{ "Title" "Url" "Summary" }
[ tag-named children>string ] curry* map
first3 <result>
] map ;

: yahoo-url ( -- str )
"http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=Factor-search&query=" ;

: query ( search num -- url )
[
yahoo-url %
swap url-encode %
"&results=" % #
] "" make ;

: search-yahoo ( search num -- seq )
query http-get 2nip
[ "Search failed" throw ] unless*
string>xml parse-yahoo ;

I wonder how long this same code is in other languages.

Update: Code updated to work with Factor .91

2 comments:

Hans Schmid said...

Hi Daniel,

I can't get your code working. It crashes in parse-yahoo at "get-name-tags". Any idea? I use the latest version of Factor (0.87).

Bye,
Hans :-)

Falicon said...

Nice example! For the record, here is some generic Ruby code that does the same thing (since you asked how long it would be in another language -- I won't even bother to show the length for Java!)

require 'net/http'
require 'rexml/document'
include REXML

query = "fantasy%20football"

newurl = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=faliconprogramming&query=#{query}&results=3&start=1"
result = Net::HTTP.get(URI(newurl))
doc = REXML::Document.new Net::HTTP.get(URI(newurl))
doc.root.each_element do |res|
puts res
puts res[0].text.to_s
puts "\n\n"
end