John Benediktsson: The Twelve Days of Christmas
Programming Praxis posted a task to write a program to print the words to The Twelve Days of Christmas song. We are going to solve it in Factor. We start off by defining all the gifts received on each day: CONSTANT: gifts { Then we iterate through the days, gathering all the gifts in reverse for each day, and formatting them, and wrapping to 72 columns of text for display. gifts [ Which gives us these words:
John Benediktsson: AnyBar
AnyBar is a macOS status indicator that displays a "colored dot" in the menu bar that can be changed programatically. What it means and when it changes is entirely up to the user. You can easily install it with Homebrew-cask: $ brew cask install anybar The README lists a number of alternative clients in different programming languages. I thought it would be fun to show how to use it from Factor. Since AnyBar responds to AppleScript (and I added support for AppleScript a few years ago), we could do this: USE: cocoa.apple-script The AnyBar application also listens to a UDP port (default: 1738) and can be instructed to change from a Terminal using a simple echo | nc command: $ echo -n "blue" | nc -4u -w0 localhost 1738 Using our networking words similarly is pretty simple: "blue" >byte-array "127.0.0.1" 1738 <inet4> send-once But if we wanted to get more fancy, we could use symbols to configure which AnyBar instance to send to, with default values to make it easy to use, and resolve-host to lookup hostnames: SYMBOL: anybar-host AnyBar is a neat little program! John Benediktsson: Reverse Factorial
A few years ago, I wrote about implementing various factorials using Factor. Recently, I came across a programming challenge to implement a "reverse factorial" function to determine what factorial produces a number, or none if it is not a factorial. To do this, we examine each factorial in order, checking against the number being tested: : reverse-factorial ( m -- n ) And some unit tests:
John Benediktsson: Gopher Server
A few days ago, I noticed a post about building a Gopher Server in Perl 6. I had already implemented a Gopher Client in Factor, and thought it might be fun to show a simple Gopher Server in Factor in around 50 lines of code. Using the io.servers vocabulary, we will define a new multi-threaded server that has a directory to serve content from and hostname that it can be accessed at: TUPLE: gopher-server < threaded-server When a file is requested, it can be streamed back to clients: : send-file ( path -- ) The Gopher protocol is defined in RFC 1436 and lists a few differentiated file types. We use the mime.types vocabulary to return the correct one. : gopher-type ( entry -- type ) When a directory is requested, we can send a listing of all the sub-directories and files it contains, sending their relative path to the root directory being served so they can be requested properly by the client: :: send-directory ( server path -- ) To know which path was requested, we read the line, split on the first tab, carriage return, or newline character we see: : read-gopher-path ( -- path ) With all of that built, we can now implement a word to handle a client request: M: gopher-server handle-client* Initializing a : <gopher-server> ( directory port -- server ) This is available in the gopher.server vocabulary with a few improvements such as:
John Benediktsson: Cuckoo Filters
A Cuckoo filter is a Bloom filter replacement that allows for space-efficient probabilistic membership checks. Cuckoo filters provide the ability to add and remove items dynamically without significantly degrading space and performance. False positive rates are typically low. This data structure is explained by Bin Fan, Dave Andersen, Michael Kaminsky, and Michael Mitzenmacher in two papers: Cuckoo Filter: Better Than Bloom and Cuckoo Filter: Practically Better Than Bloom. There is also an implementation in C++ that can be referred to. The Cuckoo filter is basically a dense hash table that can support high load factors (up to 95%) without degraded performance. Instead of storing objects, we will store a hashed fingerprint. BucketsFirst, we need to create a number of buckets. Each bucket will hold 4 fingerprints. Load factors over 96% will cause us to grow our capacity to the next-power-of-2. ! The number of fingerprints to store in each bucket Making our buckets is then just an array of arrays: : <cuckoo-buckets> ( capacity -- buckets ) Given a fingerprint, we can check if it is in a bucket by calling member?: : bucket-lookup ( fingerprint bucket -- ? ) To insert a fingerprint into the bucket, we find the first empty slot and replace it with the fingerprint. We return a boolean value indicating if we were able to insert it or not: : bucket-insert ( fingerprint bucket -- ? ) To delete a fingerprint, we finding its index (if present) and set it to false. : bucket-delete ( fingerprint bucket -- ? ) If the bucket is full, we need to be able to swap a fingerprint into the bucket, replacing/removing an existing one: : bucket-swap ( fingerprint bucket -- fingerprint' ) HashingOur hashing strategy will be to generate the SHA-1 hash value for a given byte-array, splitting it into two 32-bit values (a 32-bit fingerprint, and a 32-bit index value). We will also generate an alternate index value as well using a constant from the MurmurHash to mix with the primary index: : hash-index ( hash -- fingerprint index ) Insert/Lookup/DeleteOur Cuckoo filter holds our buckets: TUPLE: cuckoo-filter buckets ; To insert an item into the Cuckoo filter, we calculate its ! The maximum number of times we kick down items/displace from To lookup an item, we calculate the :: cuckoo-lookup ( bytes cuckoo-filter -- ? ) To delete an item, we calculate the :: cuckoo-delete ( bytes cuckoo-filter -- ? ) This is available in the cuckoo-filters vocabulary along with some tests, documentation, and a few extra features. John Benediktsson: Backticks
Most languages support running arbitrary commands using something like the Linux system function. Often, this support has both quick-and-easy and full-featured-but-complex versions. In Python, you can use os.system: In Ruby, you can use system as well as "backticks": Basically, the difference between "system" and "backticks" is:
Factor has extensive cross-platform support for launching processes, but I thought it would be fun to show how custom syntax can be created to implement "backticks", capturing and returning standard output from the process: SYNTAX: ` You can use this in a similar fashion to Ruby or Perl: IN: scratchpad ` ls -l` Note: This syntax currently requires a space after the leading backtick. In the future, we have plans for an improved lexer that removes this requirement. This is available in the backticks vocabulary. John Benediktsson: Clock Angles
Programming Praxis posted about calculating clock angles, specifically to: Write a program that, given a time as hours and minutes (using a 12-hour clock), calculates the angle between the two hands. For instance, at 2:00 the angle is 60°. Wikipedia has a page about clock angle problems that we can pull a few test cases from: The hour hand moves 360° in 12 hours and depends on the number of hours and minutes (properly handling midnight and noon to be :: hour° ( hour minutes -- degrees ) The minute hand moves 360° in 60 minutes: : minute° ( minutes -- degrees ) Using these words, we can calculate the clock angle from a time string: : clock-angle ( string -- degrees ) John Benediktsson: left-pad
In the wake of an epic ragequit where Azer Koçulu removed all of his modules from npm (the node.js package manager), there have been so many entertaining discussions and explanations covering what happened. Today, Programming Praxis posted the leftpad challenge, pointing out that the original solution ran in quadratic time due to it's use of character-by-character string concatenation (but not pointing out that it only works with strings). First, the original code in Javascript: function leftpad (str, len, ch) { Now, a (simpler? faster? more general?) version in Factor: :: left-pad ( seq n elt -- newseq ) Using it, you can see it works: IN: scratchpad "hello" 3 CHAR: h left-pad . And it even works with other types of sequences: IN: scratchpad { 1 2 3 } 3 0 left-pad . I should also point out that Factor has pad-head that does this in the standard library and node.js has a pad-left module that solves the quadratic time problem (but still only works with strings). |
Blogroll
planet-factor is an Atom/RSS aggregator that collects the contents of Factor-related blogs. It is inspired by Planet Lisp. |