Chapter 39. Literal List

Represent language expression with a literal list.

       martin.follows("WardCunningham", "bigballofmud", "KentBeck", "neal4d");

39.1 How It Works

A Literal List is a language construct for forming a list data structure. Many languages provide a direct syntax for Literal List. The most obvious of these is Lisp’s (first second third); Ruby is similar [first, second, third] but not quite as elegant. These structures usually allow lists to be nested; indeed, one way of looking at an entire Lisp program is as a nested list.

Literal Lists are usually used in a function call; the parent function will then take the elements of the list and process them in some way.

Mainstream C-based languages don’t provide a useful nested list syntax. There are literal arrays {1, 2, 3} but they often allow only constants or literals inside them, unlike a general syntax which permits any symbol or expression.

One way to get around this problem is to use varargs functions, such as companions(jo, saraJane, leela). In a strongly typed language, these elements will all need to be of the same type to work in a varargs call.

39.2 When to Use It

Literal List may work well when nested inside another element, most often a function call, using a logical grammar such as (parent ::= child*). Often, the items in the list are function calls themselves, so Literal Lists can make Nested Function workable. If you look at the examples for Nested Function, you’ll see that a Literal List is usually present as a varargs function. (The examples there also talk about some of the issues in this combination, particularly in the presence of strong typing.)

Even if your host language has native syntax for Literal Lists, you’re usually better off using a varargs function if that list is used in a function call. That is, I prefer companions(jo, saraJane, leela) to companions([jo, saraJane, leela]).

It is possible to form just about any DSL using only Literal Lists, essentially mimicking Lisp. This is, obviously, a natural way to write in Lisp, but little more than a fun exercise in other languages where it’s more natural to combine lists with other forms of expression.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.235.188