Tuesday, July 19, 2011

One-Liners

Inspired by a blog post about "one-liners" in Clojure, I thought I'd demonstrate a few small pieces of Factor code doing some similar things:

Using the map word, we can apply a "doubling" quotation to each element.
( scratchpad ) { 4 8 15 16 23 42 } [ 2 * ] map .
{ 8 16 30 32 46 84 }
We can easily calculate the sum of a sequence (here the numbers 1 through 1000):
( scratchpad ) 1000 [1,b] sum .
500500
We check if any of a list of words are within a string:
( scratchpad ) { "factor" "concatenative" "stack-based" }
               [ "factor is awesome" subseq? ] any?
You can easily read the file-contents, or file-lines, with a specified encoding (e.g., UTF-8):
( scratchpad ) "/path/to/file.txt" utf8 file-contents
Sing the four verses to the "Happy Birthday" song:
( scratchpad ) 4 [1,b] [
                   "Happy Birthday " write
                   3 = "dear NAME" "to You" ? print
               ] each
Happy Birthday to You
Happy Birthday to You
Happy Birthday dear NAME
Happy Birthday to You
Use filter (or even partition) with some selection criteria:
( scratchpad ) { 49 58 76 82 88 90 } [ 60 > ] filter .
{ 76 82 88 90 }
Use the http.client vocabulary to access a web service, and then the xml vocabulary to parse the result from a string. You could use the json.reader vocabulary to parse JSON responses.
( scratchpad ) "http://search.twitter.com/search.atom?q=factor"
               http-get nip string>xml
Check the HTTP headers to find the version of a server used by a web server:
( scratchpad ) "http://apple.com" http-get drop
               header>> "server" swap at .
"Apache/2.2.3 (Oracle)"
Use infimum and supremum to find the minimum and maximum, respectively, of a list (alternatively, you could use my maximum/minimum functions):
( scratchpad ) { 14 36 -7 46 98 } infimum .
-7

( scratchpad ) { 14 36 -7 46 98 } supremum .
98
Parse a string into groups of two characters, then interpret those as hex values of characters, mapping the output as a string:
( scratchpad ) "474e552773204e6f7420556e6978"
               2 <groups> [ 16 base> ] "" map-as .
"GNU's Not Unix"
Use concurrency.combinators to perform certain tasks in parallel with futures:
( scratchpad ) { 1 0 -1 } [ 2 + ] parallel-map .
{ 3 2 1 }

No comments:

Post a Comment