​Relations between recursion, stacks, and queues

For the sake of discussion, let’s consider a recursive and an iterative function that converts a number to a list.

(define (number->list l)
  (if (= l 0)
      '()
      (cons
       (remainder l 10)
       (number->list (quotient l 10)))))

(define (number->list-iter l acc)
  (if (= l 0)
      acc
      (number->list-iter
       (quotient l 10)
       (cons (remainder l 10) acc))))

Calling the functions produce:

> (number->list 123)
'(3 2 1)
> (number->list-iter 123 '())
'(1 2 3)

Further, let’s consider this same function rewritten in JavaScript, but implemented with stacks and queues instead of recursion:

function numbertolist_stack(n) {
        var stack = [n];

        while (stack.length) {
                var x = stack.pop();
		stack.push(x % 10);

                if (parseInt(x / 10)) {
                        stack.push(parseInt(x / 10));
                } else {
                        break;
                }
        }

        return stack;
}

function numbertolist_queue(n) {
        var queue = [n];

        while (queue.length) {
		var flag = false;
                var x = queue.shift();

                if (parseInt(x / 10)) {
                        queue.push(parseInt(x / 10));
		} else {
			flag = true;
		}

		queue.push(x % 10);

                if (flag) {
                        break;
                }
        }

        return queue;
}

So, now we have:

> numbertolist_stack(123)
[ 3, 2, 1 ]
> numbertolist_queue(123)
[ 1, 2, 3 ]

So, in terms of cons, what we can conclude is that recursion can be viewed as a stack, and tail recursion can be viewed as a queue. For if we haven’t worked in terms of cons, we can rewrite the Scheme iter function to use (append acc (list (remainder l 10))) instead of cons and achieve the same effect as number->list.

However, note that most interpreters that contain an implementation of tail call optimization wouldn’t probably implement a queue, but only a fixed set of variables in order to save space.

Another interesting observation is that we can look at it in terms of associativity (think foldr and foldl). foldr is implemented using a stack, and foldl is implemented using a queue, so that gives an idea in terms of associativity.

Or that we can implement depth-first search with a stack and breadth-first search with a queue.

IMHO, discovering relations like this is fun 🙂

Recursive and iterative processes

Let’s consider the following code in Scheme:

#lang racket
(define (add-deferred x)
(if (eq? x 0) 0 (+ x (add-deferred (- x 1)))))

(add-deferred 3)
;(add-deferred 3)                   =
;(3 + (add-deferred 2))             =
;(3 + (2 + (add-deferred 1)))       =
;(3 + (2 + (1 + (add-deferred 0)))) =
;(3 + (2 + (1 + 0))) ## evaluate now

(define (add-iter x acc)
(if (eq? x 0) acc (add-iter (- x 1) (+ acc x))))

(add-iter 3 0)
;(add-iter 3 0) = ## evaluate
;(add-iter 2 3) = ## evaluate
;(add-iter 1 5) = ## evaluate
;(add-iter 0 6) = 9

And in C:

#include <stdio.h>

int add(int x) {
if (x == 0) {
return 0;
}

return x + add(x - 1);
}

int add_iter(int x, int acc) {
if (x == 0) {
return acc;
}

return add_iter(x - 1, acc + x);
}

int main() {
printf("%d\n", add(3));
printf("%d\n", add_iter(3, 0));
}

And then this quote from SICP:

In contrasting iteration and recursion, we must be careful not to confuse the notion of a recursive process with the notion of a recursive procedure. When we describe a procedure as recursive, we are referring to the syntactic fact that the procedure definition refers (either directly or indirectly) to the procedure itself. But when we describe a process as following a pattern that is, say, linearly recursive, we are speaking about how the process evolves, not about the syntax of how a procedure is written. It may seem disturbing that we refer to a recursive procedure such as fact-iter as generating an iterative process. However, the process really is iterative: Its state is captured completely by its three state variables, and an interpreter need keep track of only three variables in order to execute the process.

One reason that the distinction between process and procedure may be confusing is that most implementations of common languages (including Ada, Pascal, and C) are designed in such a way that the interpretation of any recursive procedure consumes an amount of memory that grows with the number of procedure calls, even when the process described is, in principle, iterative. As a consequence, these languages can describe iterative processes only by resorting to special-purpose “looping constructs” such as do, repeat, until, for, and while.
The implementation of Scheme does not share this defect. It will execute an iterative process in constant space, even if the iterative process is described by a recursive procedure. An implementation with this property is called tail-recursive. With a tail-recursive implementation, iteration can be expressed using the ordinary procedure call mechanism, so that special iteration constructs are useful only as syntactic sugar.

Now since C doesn’t have tail call optimization, both calls actually produce a recursive process, that is the stack frame size grows with each call, while with Scheme the stack grows only in the case of a non-iterative process.

Property of squares

Consider the following task:
Print the first 100 squares using at most one loop. The constraints are that you are not allowed to use multiplication or functions.

To tackle this one, we will have to use one interesting property of the squares that I noticed while taking my kid to school. At the school, there was a table with all natural numbers listed from 1 to 100. While looking at it, I noticed the distances between the squares kept increasing by 2k + 1 for every kth square.

So for example, from 1 to 4 (the first square), the distance is 3. Since this is the first square, k = 1 so 2*1 + 1 = 3. The distance from 4 to 9 (the second square) is 5. Since this is the second square, k = 2 so 2*2 + 1 = 5. And so on.

Naturally I tried to generalize this and came to the following recurrent relation:

n_0 = 1
n_k = n_{k - 1} + 2k + 1

Before we use this relation in our program, we will first prove its correctness.

We will prove that n_k = (k + 1)^2 by induction.

The base case is k = 0: n_0 = 1 = 1^2 which is true. Now, we assume that n_k = (k + 1)^2. If we add 2k + 3 to both sides, we get n_{k + 1} = n_k + 2k + 3 = (k + 1)^2 + 2k + 3 = k^2 + 4k + 4 = (k + 2)^2. Thus the identity is proven.

Now, here is our simple program:

var s = 1;
for (var i = 1; i <= 100; i++) {
    console.log(s);
    s += i + i + 1;
}

React redux tutorial

I just finshed the Redux tutorial from Egghead: https://egghead.io/courses/getting-started-with-redux.

It is a very good tutorial and it starts from building a React app using Redux, and then proceeds by refactoring it and showing some cool tips and tricks to make the code more readable and maintenable.

Here is an experimental project I built in the meantime: https://github.com/bor0/notes.

Here are the notes I took during the tutorial, with the hope someone finds them useful.

Decoupling for re-use:
Presentation component => only UI no behaviour = function, pass props as args
Container component => data and behaviour for presentational component = class, use this.props for props

this.forceUpdate() forces re render

Use function instead of class when possible

Change function to =>

Class Provider: React.Component.getChildContext => { store }
<Provider store=a> <App /> </Provider>
Retrieve context by const { store } = this.context in App.
App.contextTypes = Provider.contextTypes = { store: React.propTypes.object }

Use link components to help decoupling

1. Redux
2. React
3. Refactoring code to containers and components
4. React-redux for Provider and passing store using context
5. React-redux with connect and mapStateToProps to avoid Link classes

Separate presentation components and connect them with the store by using react-redux

No in-line dispatch of actions. Make the actions explicit by adding separate function for each.

Mega quick introduction to WordPress plugin development

I took these notes myself during my trial at Automattic. I used them as a reference. Almost all of it is based on the official WordPress documentation.

  • Database Diagram
  • Comments (wp_comments) are a feature of blogs which allow readers to respond to Posts. Typically readers simply provide their own thoughts regarding the content of the post, but users may also provide links to other resources, generate discussion, or simply compliment the author for a well-written post.
  • Terms/categories (categories) for both posts and links and the tags for posts are found within the wp_terms table. Posts are associated with categories and tags from the wp_terms table and this association is maintained in the wp_term_relationships table.
  • Extending WP_List_Table example from Sensei
  • Meta box (during post edit) example from Sensei
  • Analysis = Submenu page (add_submenu_page()), Sensei = Menu page (add_menu_page())

  • Saving Plugin Data to the Database
    • Post Meta (a.k.a. Custom Fields). Appropriate for data associated with individual posts, pages, or attachments. See post_meta Function Examples, add_post_meta(), and related functions.
    • Custom Taxonomy. For classifying posts or other objects like users and comments and/or for a user-editable name/value list of data consider using a Custom Taxonomy, especially when you want to access all posts/objects associated with a given taxonomy term. See Custom Taxonomies.
    • Create a new, custom database table. This method is appropriate for data not associated with individual posts, pages, attachments, or comments — the type of data that will grow as time goes on, and that doesn’t have individual names. See Creating Tables with Plugins for information on how to do this.
  • Custom post types
    • WordPress can hold and display many different types of content. A single item of such a content is generally called a post, although post is also a specific post type. Internally, all the post types are stored in the same place, in the wp_posts database table, but are differentiated by a column named post_type.
    • Custom post types are new post types you can create. A custom post type can be added to WordPress via the register_post_type() function.
  • Hooks
    • Actions are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying an administration screen. An Action is a custom PHP function defined in your plugin (or theme) and hooked, i.e. set to respond, to some of these events. The event can be an internal one from WP (see https://codex.wordpress.org/Plugin_API/Action_Reference) or a custom one.
      • Create a PHP function that should execute when a specific WordPress event occurs, in your plugin file.
      • Hook this function to the event by using the add_action() function.
      • Put your PHP function in a plugin file, and activate it (manually by calling do_action()).
    • Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser). The filter can be an internal one from WP (see https://codex.wordpress.org/Plugin_API/Filter_Reference) or a custom one.
      • Create the PHP function that filters the data.
      • Hook to the filter in WordPress, by calling add_filter().
      • Put your PHP function in a plugin file, and activate it (manually by calling apply_filters()).
    • In some cases, you may find that you want your plugin to disable one of the actions or filters built into WordPress, or added by another plugin. You can do that by calling remove_filter('filter_hook','filter_function') or remove_action('action_hook','action_function').
    • Actions are similar to filters, where filters return a value and actions don’t.
  • Besides the hooks (actions and filters) described above, another way for a plugin to modify WordPress’s behavior is to override WordPress functions. In fact, there is a small set of functions WordPress intends for plugins to redefine. These are called Pluggable Functions and they are defined in wp-includes/pluggable.php. WordPress loads these functions only if they are still undefined after all plugins have been loaded. For more details examine wp-settings.php file.
  • The Settings API (wp_options), added in WordPress 2.7, allows admin pages containing settings forms to be managed semi-automatically. It lets you define settings pages, sections within those pages and fields within the sections.
  • The Shortcode API is a simple set of functions for creating WordPress shortcodes for use in posts and pages. For instance, the following shortcode (in the body of a post or page) would add a photo gallery of images attached to that post or page: [gallery]
    • Minimal example: add_shortcode( 'gallery', function() { return "Gallery" } );