Cicadas

All Chirping

from beginner's mind

finding delight and gratitude in dialogues of recursion...

ċuŋkṡi asks what generations means she interprets Girard for her pretend day care poetry, a fine dessert

i type a document, a program, a program parses the document into a program a program to change the program that is the document soft where...

“that's the heart that if it gets broken, everyone will stop loving each other. and its glass.” she says

 
Read more...

from fables

The Trout and The River's Flow

Trout were swimming downstream in their river and a few began to complain: I wish this river flowed elsewhere, for as it is, we must weave and wind around all manner of hazards. Logs, rocks, noxious plants – all these block our way. And, worst of all, a choke point sits ahead where the greedy grizzly waits to easily slap us out of the water as we pass. We might as well be fish in a barrel.

One fat trout, contented with long life and great luck, spoke: but what are we to do? I agree that this river could be better, but we're stuck here like it or not. We're not beaver who can dam the river to change its flow. We're not ducks who can take flight whenever we wish. This river isn't ideal, but it nevertheless provides our home.

Another trout, young and dissatisfied with the senior's proclamation, replied somewhat cryptically: there is but one thing we trout can do.

A week went by.

This young trout reappeared and shouted “to the choke point!”. At those words, a large fraction of the trout crowded into the choke point where the greedy grizzly waited. So many filled the space that the flow of water was stopped. And even though the grizzly greedily snatched up trout after trout for its feast, the water began to spill out in another direction.

 
Read more...

from drexnexlo

Old Blue

From the mountain he would come, about halfway through our visit to lay on the deck near the table and the food, by the railing that looked down the slope and to the creek. We'd have cherry seed spitting contests, Blue underfoot – cherries from Washington, sweet dying cheeks and tongues, over the side, I don't think we ever measured who won, and how can you see a cherry seed land into a field of grass when the summer wind is tickling your scalp and camp robbers sing in the pines? I can't say I was friends with Old Blue, but at the time I imagined it very so. Blue was a mountain dog and he had little time for play or games, but he was old and he was tame and he liked to be around people, and so I came to love him and expect him each visit, though he was a complete mystery. Nobody knew where Old Blue came from and he would vanish off into the woods at dusk. He would appear out of nowhere – perhaps a week or so into a summer stay – around supper of course or lunch at times. We thought he belonged to the cabin across the glade, the next road down – the one that turned to an old logging road about a quarter mile up, but Arthur talked to them and they knew Blue, but knew not where he came. Forest Green was too far, and the small cluster of cabins across the highway was scarcely inhabited. So Blue lived, seemingly feral in the woods and came around each summer to pay us company and beg some gristle. In my mind he was free and fought bears and mountain lions on a daily basis. So I began to watch the forest path, as I play among the trees and creek – up through the meadow beyond where I should venture alone, but often did. I would imagine I'd see Blue or a bear – patterned with the leaves and needles of pine. A bear beyond the cattle gate, who couldn't cross the metal grate, I'd peer as though my eyes were made of magma, so wishing and forceful – past fallen trees and rotten logs and ferns, please let me see the black tuft of a bears ear, or a hear an unfamiliar sound crying from the ravine.

 
Read more...

from drexnexlo


Eucalyptus

On my days off, sometimes I would ride down to the Berkeley Marina to the Seabreeze Cafe to eat fish and chips with a can of Tecate and watch the seagulls and other birds who I did not know, and eye my sketchbook.... next time, next time.

There was a giant and grand old eucalyptus tree that stood there right at the entrance to the jetty - in Berkeley Meadow, and I think there were more than one, but the one I remember was huge. If you ever saw it, you'd remember it too. I don't know how fast eucalyptus trees grow, but this one seemed to be over a century old, its olive colored leaves and seeds such I had never seen before. I came there with friends or alone to this tree and sat beneath it, back against bark and enjoyed its long cast shadow among the grass and dirt of the earth. I must have seen a eucalyptus before, but I never noticed one until now. Vince, Catherine, and I couldn't get our combined arms around it - or at least that's how I remember it going. The first time we saw it, Vince and I stuffed our pockets with seeds and brought them back to our apartment off Ashby and Shattuck and we placed them along the windowsill that looked out behind our kitchen sink. From this window we could see the sun set over west Berkeley - where lie the marina and tree, but there was never an indication of water or the bay, or the city beyond. Those seeds sat there and glowed in the sunlight, occasionally getting misted by soap or water, I think for the entire time we lived there. When we moved out, I suppose they were tossed into the trash or chucked into the shrubs outside the building.

There was one day, while visiting from Davis several years later- I rode over to the park and saw the trees all gone. I had thought I made a wrong turn somewhere even though I knew that was not possible. Signs were posted about invasive species removal and natural shorelines restored. Couldn't they make an exception, out of respect for a being so old and beautiful? There had to have been a moment of hesitation in the axeman's hand. There had to have been, right?


 
Read more...

from aaron

Ruby On-Ramp Questions and Answers

Describe – in your own language – Bounded Context

Oh boy, I am not familiar with this term. Can I make an educated guess? No, it wouldn't be a very good one; both “bounds” and “contexts” are pretty general ideas and could mean a number of different things.

Do you prefer ERB or HAML? Why?

I prefer HAML, because for me it's a lot cleaner and more readable, and it's simpler to type. I think meaningful indentation is a great programming concept and HAML uses it well. A good markup language should stay out of your way, and HAML is much better than ERB at that. And because it's less in-the-way, it's easier to see and comprehend the structure of the underlying HTML.

Describe what a “concern” is within Rails.

A concern is a group of methods, written inside of a Ruby Module, that can be included in other classes. It usually represents a set of shared behavior that we want to give to several different models or service objects. This has several advantages, mainly that we don't have to write the same code more than once, and we can make any future changes to the logic in one place. It also allows us to reduce the size of our model files, which are always at risk of becoming long and unwieldy.

Describe the intent of a policy. How would you write a policy to block users from creating users, but to allow a super user to create a user?

You may use any gem you'd like in your answer's code – or you may describe the logical process in your own language!

Policies allow us to control access to objects in our system. We could look at it in two ways: 1) we are granting access to an object to certain users; 2) we are blocking access to an object to certain users.

Let's assume we have a button on the Users index page that you click to create a new user. To allow only super users to do this, we need to put some code in our view that only includes this button if the current user is a super user. To do this, we would grab the current user object, which should be accessible from our view in some way, and pass it to some kind of interactor (this could be provided for us via a gem like Pundit) which essentially has a list of behaviors/actions and knows how to determine if a given user is allowed to do each of the behaviors/actions. We could call something like PolicyHelper.new(currentuser: user).createusers?, which would return true if our user can do it, and false if they can't.

We could also perform this logic in the controller (or really, in an interactor that the controller reaches out to) and then get our answer and pass it into the view, via a local. It's usually good to keep as much logic out of the views as possible.

This button, when clicked, would take us to the page with the Create User form. So we also need to do this same check as part of that controller action, in case someone navigates directly to this URL. Before we render the action's template, we do our policy check. If it comes back false, then we redirect the user to the home page, with a flash message that says something like, “Sorry, you're not allowed to perform this action.”

What is a Polymorphic Relationship? How could you use this idea in a practical way?

A polymorphic relationship exists between two domain concepts in a software system when one or both of the concepts can be represented by more than one domain objects, or in Rails terms, models. A practical example: in a billing system, you have a concept of receipts, which are paid for by payment methods. A payment method could be many different things: a credit card, a bank account, a paper check, etc. In our Rails domain model, we could have a Receipt model that has two fields, a paymentmethodtype and a paymentmethodid. The paymentmethodtype represents the name of a model that corresponds with the payment method a receipt was paid with: CreditCard, BankAccount, Check, etc. And the id tells you which particular CreditCard, BankAccount, Check, etc., paid for the receipt. The benefit to this is that a Receipt doesn't have to care what kind of thing paid for it. It can call methods on its payment_method and the different types of models can implement those methods in the way that makes sense for them.

Describe – in your own words – what a controller is generally responsible for.

The controller fields requests from a user and generates a response. Some parts of this are taken care of by the Rails framework, so that the controller gets to deal with an abstract and simplified representation of the request, and it doesn't have to actually deliver the response to the user over the wire. But everything between those two poles is the controller's responsibility. In a well-architected application, the controller will actually outsource many things to specialized interactors, like authorizing that the current user is allowed to make the request and access the data that would be returned, figuring out which data needs to populate a list on the page, etc. But the controller does need to know which interactors to call in order to get those things done. If a database operation is being performed, the controller usually needs to know if the operation succeeded or failed, and provide that information to the user accordingly, for example, by redirecting to an error page. It also needs to know what response format is being requested (for example: HTML, JSON, Javascript, etc.) and make sure it provides its response in that format, or tells the user if it can't handle the requested format.

Describe – in your own words – what a model is generally responsible for.

A model is the representation of an external domain concept in the application. It is almost always also a layer on top of the database representation of that domain concept (models are generally one-to-one with database tables). This means that it should be able to control the application's access to the database table, at least regarding “normal” user interface operations. (A developer can always bypass the model level and make direct edits to the database.) In Rails, models get a lot of functionality from an API called ActiveRecord, which allows us to give them some additional responsibilities. For example, when a new database record is being created, the model validates that the data is appropriate first, and if it's not, valid, it provides a helpful message to explain why. Models also generally perform dynamic business logic operations that are used to surface information for users. For example, in a baseball application, a Player model might represent a player's number of hits and at-bats (as stored in database fields on a “players” table). In our UI, we might want to show users the players' batting average in real table, so we could define a “batting_average” method on the Player model that divides hits into at-bats.

What is an ActiveRecord validation? When – or which method calls – make ActiveRecord validations run?

An ActiveRecord validation is a method that compares a data value that is set on a model field with a rule for what that field's values are allowed to contain. If the check fails, an error message is generated explaining why the data value is invalid, which can then be inspected by other code. For example, you can set a validation that the name field on a model must be at least 10 characters. If you then set the name on an instance of that model to a 9-character string and run the validation, it will fail and populate an error message. Validations can be run explicitly by calling “valid?” or “validate” on a model object. They also run as callbacks—pre-checks, essentially—before any operation that would update the information in the database, such as “save,” “update,” and “destroy.” The idea is that we want to make sure the data is valid first, before we put it in the database.

Describe the idea of “middleware” in Rails

One of the biggest responsibilities of the Rails framework is to take a low-level representation of a request to a web server and perform some transforming operations on it, which makes it a lot friendlier for application developers to interact with. In Rails, middleware is a term for modules of code that can be run as part of this request transformation. The framework itself comes with a bunch of middleware that already runs by default, but you can also write your own custom middleware and specify where in the “middleware chain” it will run. For example, you might maintain your own list of which browsers your application officially supports, and you want to make it easy to find out if a request is coming from a supported browser or not. You could write middleware to examine the browser identifier string from the low-level request and set a special field on the Request object, like “supported_browser?” that just returns true or false. This helps you a lot as an application developer, since you don't necessarily care precisely which browser version the user has; you might just want to add a feature that displays a message if their browser isn't supported.

Rails has a concept of a request “format” – when you're authoring views, what is the common naming convention pattern that Rails will use to automatically render certain formats?

Users can specify which format they want by putting a dot at the end of a URL, followed by the name of the format. For example, “example.com/users.json” or “example.com/users.html”. In your views folder, you can have different files corresponding to the different formats you want to render. You can also render the response directly from the controller, as is often done in the case of JSON (since the request is likely coming from some automated process rather than a person typing in a URL). The special “respond_to” controller method takes a block in which you can specify custom handling for any request format you want to support, and Rails will invoke your logic based on the incoming format.

What is “ActiveRecord” and what usually extends it?

ActiveRecord is an ORM, which is a type of software library that provides a higher-level interface to a database. It maps database tables to models, and gives the models a rich API for interacting with the data in the underlying table. With ActiveRecord, you (usually) don't need to worry about whether your app's database is postgres, MySQL, sqlite, etc., because it comes with adapters that provide you a common interface to work with and know how to translate the ActiveRecord methods you call into database-specific statements. This way, you can learn one set of operations and yet be able to interact with all kinds of different databases. If you're doing something really complicated, you might still need to interact directly with the database in its own language, but the proposition ActiveRecord makes is that you'll rarely need to do this, and most of the time you can just use its much simpler and friendlier API.

Describe – in your own words – the purpose of a “migration”. What are some challenges you would face when working as a team when you do not have the idea of “migrations” available to you?

In the old days, any changes that needed to be made to a database's schema were hidden away from the applications that were using that database. This makes it pretty difficult to keep the schema and the application code in sync. But Rails provides the ability to make your database schema changes from inside the application. It envisions this process as a series of events called “migrations,” which are sets of discrete schema changes. Migrations can be as small as changing the default of a boolean column from false to true, or as large as adding several new tables to the database. Because each of these migrations is defined in a single file in your application, they also provide a single point at which you can manage any changes you need to make to your data before or after the schema change. For example, if you write a migration to set the maximum length of a string column to 20, you first need to ensure that all values in that column are 20 or less; you can run this code directly in your migration. In addition to make this an easy way to update your production database, other devs on the project can also run the migrations to keep their local database in sync. This also gives you an easy way to roll back to a previous state if the changes didn't work out. Without migrations, team members would be responsible for keeping their own local database in sync with the main project, and they would have to be very careful about coordinating their changes to avoid schema conflicts.

Describe in detail how Rails will process a POST request to, say, create a new student in an application at the /students/new path. I'm looking for even a numbered list of what code gets executed and in what order?

https://github.com/getflywheel/on-ramp-wp-engine-2022-rails-app-/blob/application/app/controllers/students_controller.rb#L18

Well, I'm not able to access that link, unfortunately. I'm also a little confused because /students/new would likely be fielding GET requests only and displaying a form, which is then what would be POSTed (but to the create path). I'm going to assume that's what this is asking about. The first thing that will happen is that Rails will be sent the data about the request from the web server (this actually happens in one of Rails's lower-level dependencies called Rack). Next, the Rails router will attempt to match the URL path to a controller and action that will handle the request, using the code in the routes.rb file. The first match it finds will get executed. Then Rails will run any callbacks that are configured for that controller action, and then call the action method itself, which will most likely render a view template (if it doesn't explicitly do so, Rails will determine which template to render based on the controller and action names) in the format specified by the URL or the controller action, or if one isn't specified, HTML. Rails then gives the resulting markup to the web server to send over the wire to the client that made the request.

What is the role of a tool like Resque or Sidekiq?

These tools allow us to run non-time-sensitive application logic asynchronously. In other words, it runs in the background, in another process on the web server, or even on another server entirely. The main benefit of these tools is that, if we have some logic to run that will take a while, we don't have to make the user wait; we can finish up handling our web request, send HTML back to the user, and do the rest of our stuff on its own schedule. For example, when a user orders a product from us, we might want to send them a confirmation email. But since emails can take time to process and send, and the user is patiently waiting on us to display a confirmation page that their order was successful, we can have Resque or Sidekiq send our email in the background. It's okay if the user gets the email a minute or two later. Another big advantage of these tools is that if there's an error running some code, they will retry it several times, according to a configurable schedule.

Describe – in your own language – Domain Context

I'm not familiar with this term either, but I feel a little more comfortable making a guess. The term “domain” in software development refers to the real-world context in which an application operates. For example, if I am writing an app to process insurance claims, I need to know some information about how this is done today. Who is eligible to submit a claim? Who needs to be notified when a claim is submitted? If a claim is fulfilled, how do we alert the submitter and send them their benefit? There may be a great deal of knowledge, rules, conventions, terminology, etc. that is part of the domain but isn't necessarily reflected directly in your application, but forms the rationale for why your app has the features and behaviors that it does. This information is essential to understanding whether the app is fulfilling its purpose and doing what it was designed to do.

What is your favorite example of an engine? Why are engines helpful?

I'm not actually sure I can name an engine off the top of my head—maybe something like Administrate?—but basically, they are like mini apps that you can “mix in” to your own app when Rails boots it, to add some common functionality that you wouldn't want to write yourself, like an admin dashboard or user management system.

What is the rails console useful for?

Oh, I use the console all day! One use case is for quickly trying out some code in the context of my application. Yeah, sometimes I just want to figure out how some Ruby code works, but often times I am working on some feature or bug fix for an app, and I need to see if my idea is going to do what I think it will do. It's nice to have access to all your app's data for these kinds of tests, with the ability to wipe any changes away when I close my console. It even allows you to overwrite application classes and methods on the fly. The console is also really useful for making data fixes in staging and production environments in a relatively safe way.

Describe – in your own words – what a view is generally responsible for.

A view is responsible for presenting some data to the user. In most cases, it is the code that is directly responsible for creating the HTML markup that will be served to the user. All matters of style and UI “look and feel” ought to be handled by the view—although there is a common pattern of providing the view with an object called a “presenter” which may have some augmented data and allows the view to stay very “dumb” and just render basic markup. The name “view” implies that you could have several different ways to view the same set of data, and you can pick which one you want to use based on who the user is, or some characteristic of the data.

Describe the intent of writing code by following the service object pattern versus the interactors pattern. What is your opinion about this pattern?

I thought these were essentially two different names for the same pattern. I love the pattern myself, as I think it allows the controllers and models to be a lot smaller and more devoted to their core responsibilities. It gives you a central place to put some unit of logic, making it more extensible, reusable, readable, and testable.

Describe the practical difference between the two testing commands bin/rspec and bin/rails test?

RSpec is a testing gem that gives you a more descriptive, natural language-like DSL for writing tests. It originated as part of the Behavior-Driven Development paradigm, the idea being that you use the tests to specify how your code behaves as opposed to what specifically it's supposed to return. In theory this decouples your tests from your implementation, but in practice, that is pretty difficult to achieve. It also doesn't come with Rails. On the other hand, bin/rails test runs your tests with Minitest, which does come with Rails and doesn't have a DSL; as the maintainer likes to say, it's “just Ruby.” It also has a module that allows you to use the more descriptive RSpec-like syntax (describe blocks, let statements, etc.).

 
Read more...

from poems

Combination Deke Slayton and Bicycle Museum

Do you think Deke Slayton ever imagined they’d make a museum (half) for him— even one of those single-room, hometown labors of love, with posterboard displays and a Bunn coffee maker?

Or was he too busy riding his bike through the luscious summer fields, staring into the sky, dreaming of space?

 
Read more...

from fables

The Falling Snake

An eagle had captured a snake for supper. But as the eagle ascended toward her aerie, the snake, now far above the canyon floor that was its home, managed to wrestle free.

As the snake plummeted back down to earth, he realized that his doom was now unavoidable.

“Well,” thought the snake, “I might as well enjoy the view. After all, it is quite rare for a snake like me to see the world from up here.”

 
Read more...

from Parenthetical Curios

Swank Deploys

SLIME and SWANK are incredible. Start a SWANK server in your application and Whammo! You've can connect to it from the comfort of Emacs. From there you can tinker with its insides to your heart's content. This is a beta-testing dream!

Except when it isn't. Recently I deployed a Common Lisp web application where I ran into some trouble.

Trouble The First: Connection Error

So say that my service is running on server.com and SWANK is listening on port 4040. Then to connect to it I have been using ssh port forwarding:

ssh -L 4040:localhost:4040 me@server.com

So that I can then do slime-connect with localhost and 4040 as its arguments.

You might be surprised, however if you were to have used the following ssh command, which lists the local host ip of 127.0.0.1, instead of localhost:

ssh -L 4040:127.0.0.1:4040 me@server.com

For whatever reason, this fails: ssh reports a connection error. So, I had to use localhost explicitly.

Trouble The Second: SWANK-REQUIRE

The second, and more irksome issue comes up when I actually succeed at connecting via slime-connect: I immediately drop into the slime debugger. The issue seems to be that SWANK is trying to load some code upon connection. Obviously, it is not going to be able to load code unless that code is present and available on the server.

In order to get the required code into the deployed binary, I do the following prior to executing save-lisp-and-die:


(swank:swank-require 
 '(SWANK-IO-PACKAGE::SWANK-INDENTATION
   SWANK-IO-PACKAGE::SWANK-TRACE-DIALOG
   SWANK-IO-PACKAGE::SWANK-PACKAGE-FU
   SWANK-IO-PACKAGE::SWANK-PRESENTATIONS
   SWANK-IO-PACKAGE::SWANK-MACROSTEP
   SWANK-IO-PACKAGE::SWANK-FUZZY
   SWANK-IO-PACKAGE::SWANK-FANCY-INSPECTOR
   SWANK-IO-PACKAGE::SWANK-C-P-C
   SWANK-IO-PACKAGE::SWANK-ARGLISTS
   SWANK-IO-PACKAGE::SWANK-REPL))

I got the list of required modules directly from the SLIME debugger. I recompiled, redeployed, and ta-dah! It works!

#commonlisp #emacs

 
Read more...

from Parenthetical Curios

WITH-PLIST

#commonlisp

When I'm deserializing JSON, I usually end up with a property list, also called a plist (I pronounce it “Pea List”). But extracting values from plists using getf over and over again gets tedious.

Common Lisp already has with-slots and with-accessors for convenient access to CLOS objects, so why not a with-plist for convenient access to plist values?

What should with-plist do exactly? Let's look at with-slots for guidance.

WITH-SLOTS as a Guide

Observe the following:


;; define a class to test with-slots with 
(defclass abc ()
  ((a :initform 0)
   (b :initform 0)
   (c :initform 0)))

(let ((ob (make-instance 'abc))) 
  ;; bind slots by name or give a local-name to a slot binding
  (with-slots (a (my-b b) (my-c c)) ob 
    (setf a 10     
          my-b 20 
          my-c 30) 
    (format t "a=~a, my-b=~a, my-c=~a~%" 
            a my-b my-c)) 
  (format t "ob's b = ~a~%" (slot-value ob 'b)))

;; the above prints:
;; a=10, my-b=20, my-c=30
;; ob's b = 20

So here you see that with-slots allows the programmer to associate accessors with an object's slots, optionally giving those accessors a name that differs from correpsonding slot's name. Furthermore, when those variables are mutated with setf, the object itself is also mutated. How does with-slots accomplish this?

To find out, lets crack it open with macroexpand and see what's inside:


(macroexpand 
 '(with-slots (a (my-b b) (my-c c)) ob 
   (setf a 10 
    my-b 20 
    my-c 30) 
   (format t "the OB has a=~a, b=~a, c=~a~%" 
    a my-b my-c)))

;; returns

(LET ((#:G252 OB))
  (DECLARE (IGNORABLE #:G252))
  (DECLARE (SB-PCL::%VARIABLE-REBINDING #:G252 OB))
  (SYMBOL-MACROLET ((A (SLOT-VALUE #:G252 'A))
                    (MY-B (SLOT-VALUE #:G252 'B))
                    (MY-C (SLOT-VALUE #:G252 'C)))
    (SETF A 10
          MY-B 20
          MY-C 30)
    (FORMAT T "the OB has a=~a, b=~a, c=~a~%" A MY-B MY-C)))

Ah-hah! It's symbol-macrolet!

The symbol macrolet replaces instances of the symbols a, my-b and my-c with slot access forms within the body of with-slots. We may profit from the same technique in the construction of with-plist.

But first, an hypothetical example of with-plist in use:

Using WITH-PLIST

Consider the following example:


(let ((pl
        (list 'name "Buckaroo Banzai"
              :age 29
              :|currentJob| "Astro-Spy Rocker")))
  (with-plist (name (age :age) (job :|currentJob|)) pl 
    (incf age) 
    (format t "~a the ~a had a birthday and is now ~a years old~%" 
            name job age) 
    pl))
;; prints out
;; Buckaroo Banzai the Astro-Spy Rocker had a birthday and is now 30 years old

;; and returns
;; (NAME "Buckaroo Banzai" :AGE 30 :|currentJob| "Astro-Spy Rocker")

Here you can see that with-plists should be able to access keys of differing types, associate names for those accessors, and update the plist by referencing those names.

If the key is an ordinary symbol (e.g name above), then you can use that symbol itself to name the accessor. Otherwise, if the key is a keyword symbol (e.g. :age and :|currentJob| above), then some kind of local name should be provided.

Otherwise it works just like with-slots.

A Draft of the Macro


(defmacro with-plist (keys plist &body body)
  (let* ((plist-var
           (gensym))
         (macrolet-bindings
           (loop for term in keys
                 when (consp term)  
                   collect (destructuring-bind (var key) term
                             `(,var (getf ,plist-var ',key)))
                 else
                   collect `(,term (getf ,plist-var ',term)))))
    `(let ((,plist-var ,plist))
       (symbol-macrolet ,macrolet-bindings ,@body))))

The macro first determines the names of the symbol-macrolet bindings before binding each one to a getf form that accesses the plist. Thats it!

 
Read more...

from Parenthetical Curios

Where's COND-LET?

I use alexandria's when-let macro more than any other common utility. After that, the next most commonly used export is if-let. It seems to me that there is a natural extension of these two macros to a cond-let. Before getting into it, however, here is an example of if-let in action:

(if-let (x (car some-list))
  (print x)
  (print "the list was empty"))

In the above if-let behaves just like if in the case that (car some-list) is NIL. But in the case that some-list has a car, that value is bound to the variable X, which can then be used.

when-let is just like when, but again, it lets you bind a variable as the result of the tested condition in case you want to use it later.

But where oh where is cond-let? Shouldn't there be one? I have found myself writing a version of cond-let a number of times in the past, usually stashed in my project's utility module. Today we'll explore an implementation that relies on the imperative macro.

But first …

Why COND-LET ?

Because sometimes you want to do something like this:


(cond
  ((cadr xs)
   (let ((x (cadr xs)))
     (do-stuff-with x)))
  ((car xs)
   (let ((x (car xs)))
     (do-stuff-with x)))
  (t
   (do-stuff-with NIL)))

The example, however contrived, illustrates an extension of when-let and if-let to the case of a cond pattern. The concept is that you often want to use the result a predicate's evaluation (here, more like a semipredicate) in the execution of code that is run on condition that predicate returned non-nil.

Seeing COND-LET

Here is a version of cond-let macro that I'm calling imperative-cond-let.


(defun do-list-stuff (xs) 
  (imperative-cond-let 
   ((:= x (cadr xs)) 
    (list :cadr x))
   ((:= x (car xs)) 
    (list :car x)) 
   (t 
    "it's NIL!")))

;; calling do-list-stuff

> (do-list-stuff (list 1 2))
(:CADR 2)

> (do-list-stuff (list 1))
(:CAR 1)

> (do-list-stuff nil)
"it's NIL!"

If you include several variables in those binding forms then the clause will execute in the case that each variable has a non-nil value:

(defun add-first-two (xs) 
  (imperative-cond-let 
    ((:= x (cadr xs) 
         y (car xs))
     (+ x y))
    ((:= x (car xs)) x)
    (t 
     0)))

;; calling add-first-two
> (add-first-two (list 1 2))
3
> (add-first-two (list 1))
1
> (add-first-two (list ))
0

Defining IMPERATIVE-COND-LET


(defmacro imperative-cond-let (&body clauses)
  (let ((imperative-body 
          (loop
            for (bindings . body) in clauses
            for vars = (unless (eq t bindings)
                         (loop for var in (rest bindings) by #'cddr
                               collect var))
            collect bindings
            collect `(when (and ,@vars) 
                       (return (progn ,@body))))))
    `(imperative ,@imperative-body)))

I like this implementation because of its parsimony. For each clause, the variables bound using the convensions of the imperative macro are extracted. They are then check to all be be non-nil via (and ,@vars) and, when they are, the clause body is run and returned. In the case of a clause beginning with t, no variables are collected so that (and) is called, which returns t.

Try it out yourself! Use macroexpand to see what it expands into.

#commonlisp

 
Read more...

from Parenthetical Curios

Getting Imperative

A few weeks ago I was messing around with CLOG when I noticed a peculiar pattern. In several the excellent examples that ship with CLOG, the let* form is used to emulate an imperative style of programming. A good example of this can be found here. The faint putrescence of a code smell wafted up from that example, and, I thought, “Darn it, it should be better. It can be better!”

Isn't Common Lisp a multi-paradigm language? Why shouldn't this imperative pattern be expressed more naturally?

The result of my curiosity is a rough draft of a macro, called imperative.

The IMPERATIVE Macro

The imperative macro allows for the interleaving of binding forms with arbitrary non-binding forms without deep nesting. Here is how it might be used:

(imperative 
  (:= x 10 
      y (+ x 20) 
      z (+ x 100)) 
  (print (list x y z))
  (setf x 100) 
  (print (list :x x))
  (:= x 101) 
  (print (list :x x)) 
  (list x y z))

;; which would print
;; (10 30 110) 
;; (:X 100) 
;; (:X 101) 

;; then return 
;; (101 30 110)

Under the hood, the macro just nests LET* forms. For example, a macroexpand-1 of the above yeilds:

(BLOCK NIL
  (LET* ((X 10) (Y (+ X 20)) (Z (+ X 100)))
    (PRINT (LIST X Y Z))
    (SETF X 100)
    (PRINT (LIST :X X))
    (LET* ((X 101))
      (PRINT (LIST :X X))
      (LIST X Y Z))))

The whole thing is inside of a BLOCK so that you can return early if you wish by calling (return &optional value) anywhere inside.

The macro

It's not perfect, but here's the macro in its current form:


(defmacro imperative (&body body)
   "Evaluate expressins in BODY in sequence. Expressions that look
 like (:= VAR1 EXPR1 ...) will expand into a LET* form whose bindings
 are valid for the rest of the BODY

 E.g.

 (imperative 
   (format t \"Welcome to IMPERATIVE\") 
   (terpri)
   (:= x 10 z (+ x 20))
   (format t \"X = ~a, Z = ~a~%\" x z)
   (:= y (+ z 20))
   (format t \"Y = ~a~%\" y)
   (list x y z))

 would evaluate to:

 Welcome to IMPERATIVE    ;; <-- printed to stdout
 X = 10, Z = 30
 Y = 50

(10 50 30)     ;; <-- return value

IMPERATIVE introduces an implicit, anonymous BLOCK, and hence can be
returned from.
 "
   (labels ((binding-form-p (form)
              (and (consp form)
                   (keywordp (first form))
                   (eql := (first form))))
            (collect-bindings (bindings)
              (loop for (var expr . more) on bindings by #'cddr
                    collect (list var expr)))
            (expander (body)
              (cond
                ((null body) body)
                ((binding-form-p (first body))
                 (list (list* 'let* (collect-bindings (rest (first body)))
                              (expander (rest body)))))
                (t
                 (cons (first body)
                       (expander (rest body)))))))
     `(block () ,@(expander body))))

Good enough as a first draft.

Deodorizing?

A partial re-write of the smelly example is here:


(imperative
  (:= last-tab nil
      t1  (create-button body :content "Tab1")
      t2  (create-button body :content "Tab2")
      t3  (create-button body :content "Tab3"))
  (create-br body)

  (:=  p1  (create-div body)
       p2  (create-div body)
       p3  (create-div body :content "Panel3 - Type here")
       f1  (create-form p1)
       fe1 (create-form-element
            f1 :text
            :label (create-label f1 :content "Fill in blank:")))
  (create-br f1)

  (:= fe2 (create-form-element
           f1 :color
           :value "#ffffff" 
           :label (create-label f1 :content "Pick a color:")))
  (create-br f1)
  (create-form-element f1 :submit :value "OK")
  (create-form-element f1 :reset :value "Start Again")
  ;; .. this is a long one, but you get the idea ...
  )

I can't tell whether or not the deodorizor smells any better.

 
Read more...

from fables

The Farm Chicken and the Wild Partridge

A chicken, while walking the edge of her farm, spied a wild partridge out in the tall grasses. The partridge was too busy hunting for beetles and seeds to notice the approach of the chicken.

“Ho partridge,” clucked the chicken, “I see you are looking for food. But my you do go about it in such an odd manner.”

“That is correct,” replied the partridge, a little startled. “I am looking for a meal. But why do you call it odd? I usually have great luck in this patch of grass.”

“Well well…” began the chicken, “we farm fowl have learned a better, more reliable way to get great quantities food with far greater ease than hunting. We do not even need to travel for our meals!”

“My, my, ” spoke the partridge, “ it sounds unbelievable!”

“It is really very simple. If, that is, you have been educated on the signs.”

“Educated? Signs?” quizzed the partridge.

“That is right, we farm chickens are schooled from a young age on the superior way to find food. That is why,” said the chicken, gesturing to the other chickens darting about the farm, “we are all so magnificently plump! You can see for yourself.”

“I am curious. Do go on,” pressed the partridge.

“We have learned,” continued the chicken, beaming with pride to share her advanced knowledge with this backwoods partridge, “to listen for a piercing ringing noise. When we hear this noise, we run to the front of our coop where, without fail, a large mound of grain will have appeared.”

“Amazing,” said the partridge, “ but I am not sure I know what a ringing noise sounds like – I do not think have heard one. Hence, I would not know when to run.”

“That is because you have not been educated! Education may take work, but the benefits are worth it,” boasted the hearty chicken.

Just then, the farmer clanged his triangle and all the chickens darted for the coop where they frenzied to peck for the corn he had left.

“That's it! That's the ringing!” exclaimed the chicken. “I must be off.”

The partridge remained obscured in the tall grasses and watched in horror. His friend the chicken, flapping and clucking madly, was snatched up by the farmer who quelled her panic with a single sharp twist.

Chickens not so well educated would have acted more wisely. (Burke)

 
Read more...

from fables

The Farmer, The Desert Island, and the Gull.

A farmer, while traveling by boat to visit a distant dying sibling, got caught in a storm. The storm heaved the ship high atop a wave and dashed it down against an exposed rock, smashing it to bits. When the storm had cleared, the farmer awoke on a desert island with nothing save his clothes and a bag of seeds he intended as a gift for his sibling's family.

The island was small, just a few hundred feet across, and contained nothing, except for sand and one large rocky mound which, thankfully, provided some shade from the deadly heat.

At first, the farmer despaired and accepted the death that by all rights would soon come. But then it rained, and the farmer noticed that the rainwater collected in small divots that pocked the stony mound. “It rains frequently in these seas, I should have water for some time. Now only to fish for food.”

But fishing proved impossible. The farmer's sandals had been lost and all around the island were jagged rocks that sliced his feet to walk upon.

With nothing left to do, the farmer ate one of his seeds and planted the rest in the barren sand, stating “These will not grow in this sand, but I have nothing to lose. And besides, farming is all I know.”

The next day, the farmer awoke to the sight of a gull pecking at the sand where the seeds had been planted. Wasting no time, the farmer stripped off his breeches, crept up as quietly he could on the soft muting sand, and flung the clothes over the gull, ensnaring it. Once caught, the farmer got hold of the gull and twisted its neck, killing it. Next, using the gull's own beak, he skinned and sliced its body, cured its meat with brackish water, and dried it in the sun to jerky.

After a meal of gull jerky, the farmer said to himself “Well, I guess my planting bore a crop after all”.

With no reason to hope comes the freedom to be unreasonable.

 
Read more...

from fables

The Philosopher and The Fool.

One sunny day, shortly after a war had torn through the country, one citizen decided to walk through the city to see what remained standing. It was on this walk that he encountered a most peculiar scene: a fellow citizen seemed to be chewing off his own hand.

“Ho there,” greeted the first citizen, “what, by the gods, are you doing?”

“I should think,” replied the second citizen, “that it is quite obvious. I am separating my hand from my arm by the action of chewing.”

“Your actions are evident enough. What I lack,” pushed the first citizen,” is the reason why. Why are you mutilating yourself thusly?”

“I have heard,” explained the second,” that animals caught in traps will sometimes chew off their limbs in order to secure freedom. I have recently lost everything, and I feel an additional loss as to what to do now. I am trapped up in the jaws of indecision and sorrow, knowing not the worth of what might follow this catastrophe.”

“But... but...” insisted the first, “animals do this with a physical trap, such as a rope snare or a metal vice...”

“Ah, you are mistaken,” rebutted the second, “for there is no such thing as a physical trap. All traps are metaphysical.”

 
Read more...