diff options
| author | Michael Albinus | 2018-05-29 10:07:21 +0200 |
|---|---|---|
| committer | Michael Albinus | 2018-05-29 10:07:21 +0200 |
| commit | 8a09ec0d45cdc8fa54203a0f7cc1a8c909627497 (patch) | |
| tree | 2b7516e767bea0d86e3f819b6856841083f138b9 /doc | |
| parent | 0f48d18fd2a30f29cc3592a835d2a2254c9b0afb (diff) | |
| parent | 9d6a3ac73af66184e5bb23555b93833f6a4d9f2e (diff) | |
| download | emacs-8a09ec0d45cdc8fa54203a0f7cc1a8c909627497.tar.gz emacs-8a09ec0d45cdc8fa54203a0f7cc1a8c909627497.zip | |
Merge from origin/emacs-26
9d6a3ac73a Mention pcase as a fifth conditional form
567cb9046d Overhaul pcase documentation
4d7e54acff Use EXPVAL in docstrings of patterns defined using pcase-d...
7e8227ed68 Introduce EXPVAL for pcase, pcase-defmacro docstrings
e6de5b3d51 Ensure pcase doc shows `QPAT first among extensions
Diffstat (limited to 'doc')
| -rw-r--r-- | doc/lispref/control.texi | 967 | ||||
| -rw-r--r-- | doc/lispref/elisp.texi | 5 |
2 files changed, 758 insertions, 214 deletions
diff --git a/doc/lispref/control.texi b/doc/lispref/control.texi index 42aa3c9888d..34f5f570440 100644 --- a/doc/lispref/control.texi +++ b/doc/lispref/control.texi | |||
| @@ -38,6 +38,7 @@ structure constructs (@pxref{Macros}). | |||
| 38 | * Sequencing:: Evaluation in textual order. | 38 | * Sequencing:: Evaluation in textual order. |
| 39 | * Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}. | 39 | * Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}. |
| 40 | * Combining Conditions:: @code{and}, @code{or}, @code{not}. | 40 | * Combining Conditions:: @code{and}, @code{or}, @code{not}. |
| 41 | * Pattern-Matching Conditional:: How to use @code{pcase} and friends. | ||
| 41 | * Iteration:: @code{while} loops. | 42 | * Iteration:: @code{while} loops. |
| 42 | * Generators:: Generic sequences and coroutines. | 43 | * Generators:: Generic sequences and coroutines. |
| 43 | * Nonlocal Exits:: Jumping out of a sequence. | 44 | * Nonlocal Exits:: Jumping out of a sequence. |
| @@ -147,9 +148,11 @@ following @var{forms}, in textual order, returning the result of | |||
| 147 | @cindex conditional evaluation | 148 | @cindex conditional evaluation |
| 148 | 149 | ||
| 149 | Conditional control structures choose among alternatives. Emacs Lisp | 150 | Conditional control structures choose among alternatives. Emacs Lisp |
| 150 | has four conditional forms: @code{if}, which is much the same as in | 151 | has five conditional forms: @code{if}, which is much the same as in |
| 151 | other languages; @code{when} and @code{unless}, which are variants of | 152 | other languages; @code{when} and @code{unless}, which are variants of |
| 152 | @code{if}; and @code{cond}, which is a generalized case statement. | 153 | @code{if}; @code{cond}, which is a generalized case statement; |
| 154 | and @code{pcase}, which is a generalization of @code{cond} | ||
| 155 | (@pxref{Pattern-Matching Conditional}). | ||
| 153 | 156 | ||
| 154 | @defspec if condition then-form else-forms@dots{} | 157 | @defspec if condition then-form else-forms@dots{} |
| 155 | @code{if} chooses between the @var{then-form} and the @var{else-forms} | 158 | @code{if} chooses between the @var{then-form} and the @var{else-forms} |
| @@ -288,214 +291,6 @@ For example: | |||
| 288 | @end group | 291 | @end group |
| 289 | @end example | 292 | @end example |
| 290 | 293 | ||
| 291 | @menu | ||
| 292 | * Pattern matching case statement:: | ||
| 293 | @end menu | ||
| 294 | |||
| 295 | @node Pattern matching case statement | ||
| 296 | @subsection Pattern matching case statement | ||
| 297 | @cindex pcase | ||
| 298 | @cindex pattern matching | ||
| 299 | |||
| 300 | The @code{cond} form lets you choose between alternatives using | ||
| 301 | predicate conditions that compare values of expressions against | ||
| 302 | specific values known and written in advance. However, sometimes it | ||
| 303 | is useful to select alternatives based on more general conditions that | ||
| 304 | distinguish between broad classes of values. The @code{pcase} macro | ||
| 305 | allows you to choose between alternatives based on matching the value | ||
| 306 | of an expression against a series of patterns. A pattern can be a | ||
| 307 | literal value (for comparisons to literal values you'd use | ||
| 308 | @code{cond}), or it can be a more general description of the expected | ||
| 309 | structure of the expression's value. | ||
| 310 | |||
| 311 | @defmac pcase expression &rest clauses | ||
| 312 | Evaluate @var{expression} and choose among an arbitrary number of | ||
| 313 | alternatives based on the value of @var{expression}. The possible | ||
| 314 | alternatives are specified by @var{clauses}, each of which must be a | ||
| 315 | list of the form @code{(@var{pattern} @var{body-forms}@dots{})}. | ||
| 316 | @code{pcase} tries to match the value of @var{expression} to the | ||
| 317 | @var{pattern} of each clause, in textual order. If the value matches, | ||
| 318 | the clause succeeds; @code{pcase} then evaluates its @var{body-forms}, | ||
| 319 | and returns the value of the last of @var{body-forms}. Any remaining | ||
| 320 | @var{clauses} are ignored. If no clauses match, then the @code{pcase} | ||
| 321 | form evaluates to @code{nil}. | ||
| 322 | |||
| 323 | The @var{pattern} part of a clause can be of one of two types: | ||
| 324 | @dfn{QPattern}, a pattern quoted with a backquote; or a | ||
| 325 | @dfn{UPattern}, which is not quoted. UPatterns are simpler, so we | ||
| 326 | describe them first. | ||
| 327 | |||
| 328 | Note: In the description of the patterns below, we use ``the value | ||
| 329 | being matched'' to refer to the value of the @var{expression} that is | ||
| 330 | the first argument of @code{pcase}. | ||
| 331 | |||
| 332 | A UPattern can have the following forms: | ||
| 333 | |||
| 334 | @table @code | ||
| 335 | |||
| 336 | @item '@var{val} | ||
| 337 | Matches if the value being matched is @code{equal} to @var{val}. | ||
| 338 | @item @var{atom} | ||
| 339 | Matches any @var{atom}, which can be a keyword, a number, or a string. | ||
| 340 | (These are self-quoting, so this kind of UPattern is actually a | ||
| 341 | shorthand for @code{'@var{atom}}.) Note that a string or a float | ||
| 342 | matches any string or float with the same contents/value. | ||
| 343 | @item _ | ||
| 344 | Matches any value. This is known as @dfn{don't care} or @dfn{wildcard}. | ||
| 345 | @item @var{symbol} | ||
| 346 | Matches any value, and additionally let-binds @var{symbol} to the | ||
| 347 | value it matched, so that you can later refer to it, either in the | ||
| 348 | @var{body-forms} or also later in the pattern. | ||
| 349 | @item (pred @var{predfun}) | ||
| 350 | Matches if the predicate function @var{predfun} returns non-@code{nil} | ||
| 351 | when called with the value being matched as its argument. | ||
| 352 | @var{predfun} can be one of the possible forms described below. | ||
| 353 | @item (guard @var{boolean-expression}) | ||
| 354 | Matches if @var{boolean-expression} evaluates to non-@code{nil}. This | ||
| 355 | allows you to include in a UPattern boolean conditions that refer to | ||
| 356 | symbols bound to values (including the value being matched) by | ||
| 357 | previous UPatterns. Typically used inside an @code{and} UPattern, see | ||
| 358 | below. For example, @w{@code{(and x (guard (< x 10)))}} is a pattern | ||
| 359 | which matches any number smaller than 10 and let-binds the variable | ||
| 360 | @code{x} to that number. | ||
| 361 | @item (let @var{upattern} @var{expression}) | ||
| 362 | Matches if the specified @var{expression} matches the specified | ||
| 363 | @var{upattern}. This allows matching a pattern against the value of | ||
| 364 | an @emph{arbitrary} expression, not just the expression that is the | ||
| 365 | first argument to @code{pcase}. (It is called @code{let} because | ||
| 366 | @var{upattern} can bind symbols to values using the @var{symbol} | ||
| 367 | UPattern. For example: | ||
| 368 | @w{@code{((or `(key . ,val) (let val 5)) val)}}.) | ||
| 369 | @item (app @var{function} @var{upattern}) | ||
| 370 | Matches if @var{function} applied to the value being matched returns a | ||
| 371 | value that matches @var{upattern}. This is like the @code{pred} | ||
| 372 | UPattern, except that it tests the result against @var{upattern}, | ||
| 373 | rather than against a boolean truth value. The @var{function} call can | ||
| 374 | use one of the forms described below. | ||
| 375 | @item (or @var{upattern1} @var{upattern2}@dots{}) | ||
| 376 | Matches if one the argument UPatterns matches. As soon as the first | ||
| 377 | matching UPattern is found, the rest are not tested. For this reason, | ||
| 378 | if any of the UPatterns let-bind symbols to the matched value, they | ||
| 379 | should all bind the same symbols. | ||
| 380 | @item (and @var{upattern1} @var{upattern2}@dots{}) | ||
| 381 | Matches if all the argument UPatterns match. | ||
| 382 | @end table | ||
| 383 | |||
| 384 | The function calls used in the @code{pred} and @code{app} UPatterns | ||
| 385 | can have one of the following forms: | ||
| 386 | |||
| 387 | @table @asis | ||
| 388 | @item function symbol, like @code{integerp} | ||
| 389 | In this case, the named function is applied to the value being | ||
| 390 | matched. | ||
| 391 | @item lambda-function @code{(lambda (@var{arg}) @var{body})} | ||
| 392 | In this case, the lambda-function is called with one argument, the | ||
| 393 | value being matched. | ||
| 394 | @item @code{(@var{func} @var{args}@dots{})} | ||
| 395 | This is a function call with @var{n} specified arguments; the function | ||
| 396 | is called with these @var{n} arguments and an additional @var{n}+1-th | ||
| 397 | argument that is the value being matched. | ||
| 398 | @end table | ||
| 399 | |||
| 400 | Here's an illustrative example of using UPatterns: | ||
| 401 | |||
| 402 | @c FIXME: This example should use every one of the UPatterns described | ||
| 403 | @c above at least once. | ||
| 404 | @example | ||
| 405 | (pcase (get-return-code x) | ||
| 406 | ('success (message "Done!")) | ||
| 407 | ('would-block (message "Sorry, can't do it now")) | ||
| 408 | ('read-only (message "The shmliblick is read-only")) | ||
| 409 | ('access-denied (message "You do not have the needed rights")) | ||
| 410 | (code (message "Unknown return code %S" code))) | ||
| 411 | @end example | ||
| 412 | |||
| 413 | In addition, you can use backquoted patterns that are more powerful. | ||
| 414 | They allow matching the value of the @var{expression} that is the | ||
| 415 | first argument of @code{pcase} against specifications of its | ||
| 416 | @emph{structure}. For example, you can specify that the value must be | ||
| 417 | a list of 2 elements whose first element is a specific string and the | ||
| 418 | second element is any value with a backquoted pattern like | ||
| 419 | @code{`("first" ,second-elem)}. | ||
| 420 | |||
| 421 | Backquoted patterns have the form @code{`@var{qpattern}} where | ||
| 422 | @var{qpattern} can have the following forms: | ||
| 423 | |||
| 424 | @table @code | ||
| 425 | @item (@var{qpattern1} . @var{qpattern2}) | ||
| 426 | Matches if the value being matched is a cons cell whose @code{car} | ||
| 427 | matches @var{qpattern1} and whose @code{cdr} matches @var{qpattern2}. | ||
| 428 | This readily generalizes to backquoted lists as in | ||
| 429 | @w{@code{(@var{qpattern1} @var{qpattern2} @dots{})}}. | ||
| 430 | @item [@var{qpattern1} @var{qpattern2} @dots{} @var{qpatternm}] | ||
| 431 | Matches if the value being matched is a vector of length @var{m} whose | ||
| 432 | @code{0}..@code{(@var{m}-1)}th elements match @var{qpattern1}, | ||
| 433 | @var{qpattern2} @dots{} @var{qpatternm}, respectively. | ||
| 434 | @item @var{atom} | ||
| 435 | Matches if corresponding element of the value being matched is | ||
| 436 | @code{equal} to the specified @var{atom}. | ||
| 437 | @item ,@var{upattern} | ||
| 438 | Matches if the corresponding element of the value being matched | ||
| 439 | matches the specified @var{upattern}. | ||
| 440 | @end table | ||
| 441 | |||
| 442 | Note that uses of QPatterns can be expressed using only UPatterns, as | ||
| 443 | QPatterns are implemented on top of UPatterns using | ||
| 444 | @code{pcase-defmacro}, described below. However, using QPatterns will | ||
| 445 | in many cases lead to a more readable code. | ||
| 446 | @c FIXME: There should be an example here showing how a 'pcase' that | ||
| 447 | @c uses QPatterns can be rewritten using UPatterns. | ||
| 448 | |||
| 449 | @end defmac | ||
| 450 | |||
| 451 | Here is an example of using @code{pcase} to implement a simple | ||
| 452 | interpreter for a little expression language (note that this example | ||
| 453 | requires lexical binding, @pxref{Lexical Binding}): | ||
| 454 | |||
| 455 | @example | ||
| 456 | (defun evaluate (exp env) | ||
| 457 | (pcase exp | ||
| 458 | (`(add ,x ,y) (+ (evaluate x env) (evaluate y env))) | ||
| 459 | (`(call ,fun ,arg) (funcall (evaluate fun env) (evaluate arg env))) | ||
| 460 | (`(fn ,arg ,body) (lambda (val) | ||
| 461 | (evaluate body (cons (cons arg val) env)))) | ||
| 462 | ((pred numberp) exp) | ||
| 463 | ((pred symbolp) (cdr (assq exp env))) | ||
| 464 | (_ (error "Unknown expression %S" exp)))) | ||
| 465 | @end example | ||
| 466 | |||
| 467 | Here @code{`(add ,x ,y)} is a pattern that checks that @code{exp} is a | ||
| 468 | three-element list starting with the literal symbol @code{add}, then | ||
| 469 | extracts the second and third elements and binds them to the variables | ||
| 470 | @code{x} and @code{y}. Then it evaluates @code{x} and @code{y} and | ||
| 471 | adds the results. The @code{call} and @code{fn} patterns similarly | ||
| 472 | implement two flavors of function calls. @code{(pred numberp)} is a | ||
| 473 | pattern that simply checks that @code{exp} is a number and if so, | ||
| 474 | evaluates it. @code{(pred symbolp)} matches symbols, and returns | ||
| 475 | their association. Finally, @code{_} is the catch-all pattern that | ||
| 476 | matches anything, so it's suitable for reporting syntax errors. | ||
| 477 | |||
| 478 | Here are some sample programs in this small language, including their | ||
| 479 | evaluation results: | ||
| 480 | |||
| 481 | @example | ||
| 482 | (evaluate '(add 1 2) nil) ;=> 3 | ||
| 483 | (evaluate '(add x y) '((x . 1) (y . 2))) ;=> 3 | ||
| 484 | (evaluate '(call (fn x (add 1 x)) 2) nil) ;=> 3 | ||
| 485 | (evaluate '(sub 1 2) nil) ;=> error | ||
| 486 | @end example | ||
| 487 | |||
| 488 | Additional UPatterns can be defined using the @code{pcase-defmacro} | ||
| 489 | macro. | ||
| 490 | |||
| 491 | @defmac pcase-defmacro name args &rest body | ||
| 492 | Define a new kind of UPattern for @code{pcase}. The new UPattern will | ||
| 493 | be invoked as @code{(@var{name} @var{actual-args})}. The @var{body} | ||
| 494 | should describe how to rewrite the UPattern @var{name} into some other | ||
| 495 | UPattern. The rewriting will be the result of evaluating @var{body} | ||
| 496 | in an environment where @var{args} are bound to @var{actual-args}. | ||
| 497 | @end defmac | ||
| 498 | |||
| 499 | @node Combining Conditions | 294 | @node Combining Conditions |
| 500 | @section Constructs for Combining Conditions | 295 | @section Constructs for Combining Conditions |
| 501 | @cindex combining conditions | 296 | @cindex combining conditions |
| @@ -621,6 +416,758 @@ This is not completely equivalent because it can evaluate @var{arg1} or | |||
| 621 | @var{arg3})} never evaluates any argument more than once. | 416 | @var{arg3})} never evaluates any argument more than once. |
| 622 | @end defspec | 417 | @end defspec |
| 623 | 418 | ||
| 419 | @node Pattern-Matching Conditional | ||
| 420 | @section Pattern-Matching Conditional | ||
| 421 | @cindex pcase | ||
| 422 | @cindex pattern matching | ||
| 423 | |||
| 424 | Aside from the four basic conditional forms, Emacs Lisp also | ||
| 425 | has a pattern-matching conditional form, the @code{pcase} macro, | ||
| 426 | a hybrid of @code{cond} and @code{cl-case} | ||
| 427 | (@pxref{Conditionals,,,cl,Common Lisp Extensions}) | ||
| 428 | that overcomes their limitations and introduces | ||
| 429 | the @dfn{pattern matching} programming style. | ||
| 430 | First, the limitations: | ||
| 431 | |||
| 432 | @itemize | ||
| 433 | @item The @code{cond} form chooses among alternatives | ||
| 434 | by evaluating the predicate @var{condition} of each | ||
| 435 | of its clauses (@pxref{Conditionals}). | ||
| 436 | The primary limitation is that variables let-bound in @var{condition} | ||
| 437 | are not available to the clause's @var{body-forms}. | ||
| 438 | |||
| 439 | Another annoyance (more an inconvenience than a limitation) | ||
| 440 | is that when a series of @var{condition} predicates implement | ||
| 441 | equality tests, there is a lot of repeated code. | ||
| 442 | For that, why not use @code{cl-case}? | ||
| 443 | |||
| 444 | @item | ||
| 445 | The @code{cl-case} macro chooses among alternatives by evaluating | ||
| 446 | the equality of its first argument against a set of specific | ||
| 447 | values. | ||
| 448 | The limitations are two-fold: | ||
| 449 | |||
| 450 | @enumerate | ||
| 451 | @item The equality tests use @code{eql}. | ||
| 452 | @item The values must be known and written in advance. | ||
| 453 | @end enumerate | ||
| 454 | |||
| 455 | @noindent | ||
| 456 | These render @code{cl-case} unsuitable for strings or compound | ||
| 457 | data structures (e.g., lists or vectors). | ||
| 458 | For that, why not use @code{cond}? | ||
| 459 | (And here we end up in a circle.) | ||
| 460 | @end itemize | ||
| 461 | |||
| 462 | @noindent | ||
| 463 | Conceptually, the @code{pcase} macro borrows the first-arg focus | ||
| 464 | of @code{cl-case} and the clause-processing flow of @code{cond}, | ||
| 465 | replacing @var{condition} with a generalization of | ||
| 466 | the equality test called @dfn{matching}, | ||
| 467 | and adding facilities so that you can concisely express a | ||
| 468 | clause's predicate, and arrange to share let-bindings between | ||
| 469 | a clause's predicate and @var{body-forms}. | ||
| 470 | |||
| 471 | The concise expression of a predicate is known as a @dfn{pattern}. | ||
| 472 | When the predicate, called on the value of the first arg, | ||
| 473 | returns non-@code{nil}, the pattern matches the value | ||
| 474 | (or sometimes ``the value matches the pattern''). | ||
| 475 | |||
| 476 | @menu | ||
| 477 | * The @code{pcase} macro: pcase Macro. Plus examples and caveats. | ||
| 478 | * Extending @code{pcase}: Extending pcase. Define new kinds of patterns. | ||
| 479 | * Backquote-Style Patterns: Backquote Patterns. Structural matching. | ||
| 480 | @end menu | ||
| 481 | |||
| 482 | @node pcase Macro | ||
| 483 | @subsection The @code{pcase} macro | ||
| 484 | |||
| 485 | For background, @xref{Pattern-Matching Conditional}. | ||
| 486 | |||
| 487 | @defmac pcase expression &rest clauses | ||
| 488 | Each clause in @var{clauses} has the form: | ||
| 489 | @w{@code{(@var{pattern} @var{body-forms}@dots{})}}. | ||
| 490 | |||
| 491 | Evaluate @var{expression} to determine its value, @var{expval}. | ||
| 492 | Find the first clause in @var{clauses} whose @var{pattern} matches | ||
| 493 | @var{expval} and pass control to that clause's @var{body-forms}. | ||
| 494 | |||
| 495 | If there is a match, the value of @code{pcase} is the value | ||
| 496 | of the last of @var{body-forms} in the successful clause. | ||
| 497 | Otherwise, @code{pcase} evaluates to @code{nil}. | ||
| 498 | @end defmac | ||
| 499 | |||
| 500 | The rest of this subsection | ||
| 501 | describes different forms of core patterns, | ||
| 502 | presents some examples, | ||
| 503 | and concludes with important caveats on using the | ||
| 504 | let-binding facility provided by some pattern forms. | ||
| 505 | A core pattern can have the following forms: | ||
| 506 | |||
| 507 | @table @code | ||
| 508 | |||
| 509 | @item _ | ||
| 510 | Matches any @var{expval}. | ||
| 511 | This is known as @dfn{don't care} or @dfn{wildcard}. | ||
| 512 | |||
| 513 | @item '@var{val} | ||
| 514 | Matches if @var{expval} is @code{equal} to @var{val}. | ||
| 515 | |||
| 516 | @item @var{keyword} | ||
| 517 | @itemx @var{integer} | ||
| 518 | @itemx @var{string} | ||
| 519 | Matches if @var{expval} is @code{equal} to the literal object. | ||
| 520 | This is a special case of @code{'@var{val}}, above, | ||
| 521 | possible because literal objects of these types are self-quoting. | ||
| 522 | |||
| 523 | @item @var{symbol} | ||
| 524 | Matches any @var{expval}, and additionally let-binds @var{symbol} to | ||
| 525 | @var{expval}, such that this binding is available to | ||
| 526 | @var{body-forms} (@pxref{Dynamic Binding}). | ||
| 527 | |||
| 528 | If @var{symbol} is part of a sequencing pattern @var{seqpat} | ||
| 529 | (e.g., by using @code{and}, below), the binding is also available to | ||
| 530 | the portion of @var{seqpat} following the appearance of @var{symbol}. | ||
| 531 | This usage has some caveats (@pxref{pcase-symbol-caveats,,caveats}). | ||
| 532 | |||
| 533 | Two symbols to avoid are @code{t}, which behaves like @code{_} | ||
| 534 | (above) and is deprecated, and @code{nil}, which signals error. | ||
| 535 | Likewise, it makes no sense to bind keyword symbols | ||
| 536 | (@pxref{Constant Variables}). | ||
| 537 | |||
| 538 | @item (pred @var{function}) | ||
| 539 | Matches if the predicate @var{function} returns non-@code{nil} | ||
| 540 | when called on @var{expval}. | ||
| 541 | @var{function} can have one of the possible forms: | ||
| 542 | |||
| 543 | @table @asis | ||
| 544 | @item function name (a symbol) | ||
| 545 | Call the named function with one argument, @var{expval}. | ||
| 546 | |||
| 547 | Example: @code{integerp} | ||
| 548 | |||
| 549 | @item lambda expression | ||
| 550 | Call the anonymous function with one argument, | ||
| 551 | @var{expval} (@pxref{Lambda Expressions}). | ||
| 552 | |||
| 553 | Example: @code{(lambda (n) (= 42 n))} | ||
| 554 | |||
| 555 | @item function call with @var{n} args | ||
| 556 | Call the function (the first element of the function call) | ||
| 557 | with @var{n} arguments (the other elements) and an additional | ||
| 558 | @var{n}+1-th argument that is @var{expval}. | ||
| 559 | |||
| 560 | Example: @code{(= 42)}@* | ||
| 561 | In this example, the function is @code{=}, @var{n} is one, and | ||
| 562 | the actual function call becomes: @w{@code{(= 42 @var{expval})}}. | ||
| 563 | @end table | ||
| 564 | |||
| 565 | @item (app @var{function} @var{pattern}) | ||
| 566 | Matches if @var{function} called on @var{expval} returns a | ||
| 567 | value that matches @var{pattern}. | ||
| 568 | @var{function} can take one of the | ||
| 569 | forms described for @code{pred}, above. | ||
| 570 | Unlike @code{pred}, however, | ||
| 571 | @code{app} tests the result against @var{pattern}, | ||
| 572 | rather than against a boolean truth value. | ||
| 573 | |||
| 574 | @item (guard @var{boolean-expression}) | ||
| 575 | Matches if @var{boolean-expression} evaluates to non-@code{nil}. | ||
| 576 | |||
| 577 | @item (let @var{pattern} @var{expr}) | ||
| 578 | Evaluates @var{expr} to get @var{exprval} | ||
| 579 | and matches if @var{exprval} matches @var{pattern}. | ||
| 580 | (It is called @code{let} because | ||
| 581 | @var{pattern} can bind symbols to values using @var{symbol}.) | ||
| 582 | @end table | ||
| 583 | |||
| 584 | @cindex sequencing pattern | ||
| 585 | A @dfn{sequencing pattern} (also known as @var{seqpat}) is a | ||
| 586 | pattern that processes its sub-pattern arguments in sequence. | ||
| 587 | There are two for @code{pcase}: @code{and} and @code{or}. | ||
| 588 | They behave in a similar manner to the special forms | ||
| 589 | that share their name (@pxref{Combining Conditions}), | ||
| 590 | but instead of processing values, they process sub-patterns. | ||
| 591 | |||
| 592 | @table @code | ||
| 593 | @item (and @var{pattern1}@dots{}) | ||
| 594 | Attempts to match @var{pattern1}@dots{}, in order, | ||
| 595 | until one of them fails to match. | ||
| 596 | In that case, @code{and} likewise fails to match, | ||
| 597 | and the rest of the sub-patterns are not tested. | ||
| 598 | If all sub-patterns match, @code{and} matches. | ||
| 599 | |||
| 600 | @item (or @var{pattern1} @var{pattern2}@dots{}) | ||
| 601 | Attempts to match @var{pattern1}, @var{pattern2}, @dots{}, in order, | ||
| 602 | until one of them succeeds. | ||
| 603 | In that case, @code{or} likewise matches, | ||
| 604 | and the rest of the sub-patterns are not tested. | ||
| 605 | (Note that there must be at least two sub-patterns. | ||
| 606 | Simply @w{@code{(or @var{pattern1})}} signals error.) | ||
| 607 | @c Issue: Is this correct and intended? | ||
| 608 | @c Are there exceptions, qualifications? | ||
| 609 | @c (Btw, ``Please avoid it'' is a poor error message.) | ||
| 610 | |||
| 611 | To present a consistent environment (@pxref{Intro Eval}) | ||
| 612 | to @var{body-forms} (thus avoiding an evaluation error on match), | ||
| 613 | if any of the sub-patterns let-binds a set of symbols, | ||
| 614 | they @emph{must} all bind the same set of symbols. | ||
| 615 | @end table | ||
| 616 | |||
| 617 | @anchor{pcase-example-0} | ||
| 618 | @subheading Example: Advantage Over @code{cl-case} | ||
| 619 | |||
| 620 | Here's an example that highlights some advantages @code{pcase} | ||
| 621 | has over @code{cl-case} | ||
| 622 | (@pxref{Conditionals,,,cl,Common Lisp Extensions}). | ||
| 623 | |||
| 624 | @example | ||
| 625 | @group | ||
| 626 | (pcase (get-return-code x) | ||
| 627 | ;; string | ||
| 628 | ((and (pred stringp) msg) | ||
| 629 | (message "%s" msg)) | ||
| 630 | @end group | ||
| 631 | @group | ||
| 632 | ;; symbol | ||
| 633 | ('success (message "Done!")) | ||
| 634 | ('would-block (message "Sorry, can't do it now")) | ||
| 635 | ('read-only (message "The shmliblick is read-only")) | ||
| 636 | ('access-denied (message "You do not have the needed rights")) | ||
| 637 | @end group | ||
| 638 | @group | ||
| 639 | ;; default | ||
| 640 | (code (message "Unknown return code %S" code))) | ||
| 641 | @end group | ||
| 642 | @end example | ||
| 643 | |||
| 644 | @noindent | ||
| 645 | With @code{cl-case}, you would need to explicitly declare a local | ||
| 646 | variable @code{code} to hold the return value of @code{get-return-code}. | ||
| 647 | Also @code{cl-case} is difficult to use with strings because it | ||
| 648 | uses @code{eql} for comparison. | ||
| 649 | |||
| 650 | @anchor{pcase-example-1} | ||
| 651 | @subheading Example: Using @code{and} | ||
| 652 | |||
| 653 | A common idiom is to write a pattern starting with @code{and}, | ||
| 654 | with one or more @var{symbol} sub-patterns providing bindings | ||
| 655 | to the sub-patterns that follow (as well as to the body forms). | ||
| 656 | For example, the following pattern matches single-digit integers. | ||
| 657 | |||
| 658 | @example | ||
| 659 | @group | ||
| 660 | (and | ||
| 661 | (pred integerp) | ||
| 662 | n ; @r{bind @code{n} to @var{expval}} | ||
| 663 | (guard (<= -9 n 9))) | ||
| 664 | @end group | ||
| 665 | @end example | ||
| 666 | |||
| 667 | @noindent | ||
| 668 | First, @code{pred} matches if @w{@code{(integerp @var{expval})}} | ||
| 669 | evaluates to non-@code{nil}. | ||
| 670 | Next, @code{n} is a @var{symbol} pattern that matches | ||
| 671 | anything and binds @code{n} to @var{expval}. | ||
| 672 | Lastly, @code{guard} matches if the boolean expression | ||
| 673 | @w{@code{(<= -9 n 9)}} (note the reference to @code{n}) | ||
| 674 | evaluates to non-@code{nil}. | ||
| 675 | If all these sub-patterns match, @code{and} matches. | ||
| 676 | |||
| 677 | @anchor{pcase-example-2} | ||
| 678 | @subheading Example: Reformulation with @code{pcase} | ||
| 679 | |||
| 680 | Here is another example that shows how to reformulate a simple | ||
| 681 | matching task from its traditional implementation | ||
| 682 | (function @code{grok/traditional}) to one using | ||
| 683 | @code{pcase} (function @code{grok/pcase}). | ||
| 684 | The docstring for both these functions is: | ||
| 685 | ``If OBJ is a string of the form "key:NUMBER", return NUMBER | ||
| 686 | (a string). Otherwise, return the list ("149" default).'' | ||
| 687 | First, the traditional implementation (@pxref{Regular Expressions}): | ||
| 688 | |||
| 689 | @example | ||
| 690 | @group | ||
| 691 | (defun grok/traditional (obj) | ||
| 692 | (if (and (stringp obj) | ||
| 693 | (string-match "^key:\\([[:digit:]]+\\)$" obj)) | ||
| 694 | (match-string 1 obj) | ||
| 695 | (list "149" 'default))) | ||
| 696 | @end group | ||
| 697 | |||
| 698 | @group | ||
| 699 | (grok/traditional "key:0") @result{} "0" | ||
| 700 | (grok/traditional "key:149") @result{} "149" | ||
| 701 | (grok/traditional 'monolith) @result{} ("149" default) | ||
| 702 | @end group | ||
| 703 | @end example | ||
| 704 | |||
| 705 | @noindent | ||
| 706 | The reformulation demonstrates @var{symbol} binding as well as | ||
| 707 | @code{or}, @code{and}, @code{pred}, @code{app} and @code{let}. | ||
| 708 | |||
| 709 | @example | ||
| 710 | @group | ||
| 711 | (defun grok/pcase (obj) | ||
| 712 | (pcase obj | ||
| 713 | ((or ; @r{line 1} | ||
| 714 | (and ; @r{line 2} | ||
| 715 | (pred stringp) ; @r{line 3} | ||
| 716 | (pred (string-match ; @r{line 4} | ||
| 717 | "^key:\\([[:digit:]]+\\)$")) ; @r{line 5} | ||
| 718 | (app (match-string 1) ; @r{line 6} | ||
| 719 | val)) ; @r{line 7} | ||
| 720 | (let val (list "149" 'default))) ; @r{line 8} | ||
| 721 | val))) ; @r{line 9} | ||
| 722 | @end group | ||
| 723 | |||
| 724 | @group | ||
| 725 | (grok/pcase "key:0") @result{} "0" | ||
| 726 | (grok/pcase "key:149") @result{} "149" | ||
| 727 | (grok/pcase 'monolith) @result{} ("149" default) | ||
| 728 | @end group | ||
| 729 | @end example | ||
| 730 | |||
| 731 | @noindent | ||
| 732 | The bulk of @code{grok/pcase} is a single clause of a @code{pcase} | ||
| 733 | form, the pattern on lines 1-8, the (single) body form on line 9. | ||
| 734 | The pattern is @code{or}, which tries to match in turn its argument | ||
| 735 | sub-patterns, first @code{and} (lines 2-7), then @code{let} (line 8), | ||
| 736 | until one of them succeeds. | ||
| 737 | |||
| 738 | As in the previous example (@pxref{pcase-example-1,,Example 1}), | ||
| 739 | @code{and} begins with a @code{pred} sub-pattern to ensure | ||
| 740 | the following sub-patterns work with an object of the correct | ||
| 741 | type (string, in this case). If @w{@code{(stringp @var{expval})}} | ||
| 742 | returns @code{nil}, @code{pred} fails, and thus @code{and} fails, too. | ||
| 743 | |||
| 744 | The next @code{pred} (lines 4-5) evaluates | ||
| 745 | @w{@code{(string-match RX @var{expval})}} | ||
| 746 | and matches if the result is non-@code{nil}, which means | ||
| 747 | that @var{expval} has the desired form: @code{key:NUMBER}. | ||
| 748 | Again, failing this, @code{pred} fails and @code{and}, too. | ||
| 749 | |||
| 750 | Lastly (in this series of @code{and} sub-patterns), @code{app} | ||
| 751 | evaluates @w{@code{(match-string 1 @var{expval})}} (line 6) | ||
| 752 | to get a temporary value @var{tmp} (i.e., the ``NUMBER'' substring) | ||
| 753 | and tries to match @var{tmp} against pattern @code{val} (line 7). | ||
| 754 | Since that is a @var{symbol} pattern, it matches unconditionally | ||
| 755 | and additionally binds @code{val} to @var{tmp}. | ||
| 756 | |||
| 757 | Now that @code{app} has matched, all @code{and} sub-patterns | ||
| 758 | have matched, and so @code{and} matches. | ||
| 759 | Likewise, once @code{and} has matched, @code{or} matches | ||
| 760 | and does not proceed to try sub-pattern @code{let} (line 8). | ||
| 761 | |||
| 762 | Let's consider the situation where @code{obj} is not a string, | ||
| 763 | or it is a string but has the wrong form. | ||
| 764 | In this case, one of the @code{pred} (lines 3-5) fails to match, | ||
| 765 | thus @code{and} (line 2) fails to match, | ||
| 766 | thus @code{or} (line 1) proceeds to try sub-pattern @code{let} (line 8). | ||
| 767 | |||
| 768 | First, @code{let} evaluates @w{@code{(list "149" 'default)}} | ||
| 769 | to get @w{@code{("149" default)}}, the @var{exprval}, and then | ||
| 770 | tries to match @var{exprval} against pattern @code{val}. | ||
| 771 | Since that is a @var{symbol} pattern, it matches unconditionally | ||
| 772 | and additionally binds @code{val} to @var{exprval}. | ||
| 773 | Now that @code{let} has matched, @code{or} matches. | ||
| 774 | |||
| 775 | Note how both @code{and} and @code{let} sub-patterns finish in the | ||
| 776 | same way: by trying (always successfully) to match against the | ||
| 777 | @var{symbol} pattern @code{val}, in the process binding @code{val}. | ||
| 778 | Thus, @code{or} always matches and control always passes | ||
| 779 | to the body form (line 9). | ||
| 780 | Because that is the last body form in a successfully matched | ||
| 781 | @code{pcase} clause, it is the value of @code{pcase} and likewise | ||
| 782 | the return value of @code{grok/pcase} (@pxref{What Is a Function}). | ||
| 783 | |||
| 784 | @anchor{pcase-symbol-caveats} | ||
| 785 | @subheading Caveats for @var{symbol} in Sequencing Patterns | ||
| 786 | |||
| 787 | The preceding examples all use sequencing patterns | ||
| 788 | which include the @var{symbol} | ||
| 789 | sub-pattern in some way. | ||
| 790 | Here are some important details about that usage. | ||
| 791 | |||
| 792 | @enumerate | ||
| 793 | @item When @var{symbol} occurs more than once in @var{seqpat}, | ||
| 794 | the second and subsequent occurances do not expand to re-binding, | ||
| 795 | but instead expand to an equality test using @code{eq}. | ||
| 796 | |||
| 797 | The following example features a @code{pcase} form | ||
| 798 | with two clauses and two @var{seqpat}, A and B. | ||
| 799 | Both A and B first check that @var{expval} is a | ||
| 800 | pair (using @code{pred}), | ||
| 801 | and then bind symbols to the @code{car} and @code{cdr} | ||
| 802 | of @var{expval} (using one @code{app} each). | ||
| 803 | |||
| 804 | For A, because symbol @code{st} is mentioned twice, the second | ||
| 805 | mention becomes an equality test using @code{eq}. | ||
| 806 | On the other hand, B uses two separate symbols, @code{s1} and | ||
| 807 | @code{s2}, both of which become independent bindings. | ||
| 808 | |||
| 809 | @example | ||
| 810 | @group | ||
| 811 | (defun grok (object) | ||
| 812 | (pcase object | ||
| 813 | ((and (pred consp) ; seqpat A | ||
| 814 | (app car st) ; first mention: st | ||
| 815 | (app cdr st)) ; second mention: st | ||
| 816 | (list 'eq st)) | ||
| 817 | @end group | ||
| 818 | @group | ||
| 819 | ((and (pred consp) ; seqpat B | ||
| 820 | (app car s1) ; first mention: s1 | ||
| 821 | (app cdr s2)) ; first mention: s2 | ||
| 822 | (list 'not-eq s1 s2)))) | ||
| 823 | @end group | ||
| 824 | |||
| 825 | @group | ||
| 826 | (let ((s "yow!")) | ||
| 827 | (grok (cons s s))) @result{} (eq "yow!") | ||
| 828 | (grok (cons "yo!" "yo!")) @result{} (not-eq "yo!" "yo!") | ||
| 829 | (grok '(4 2)) @result{} (not-eq 4 (2)) | ||
| 830 | @end group | ||
| 831 | @end example | ||
| 832 | |||
| 833 | @item Side-effecting code referencing @var{symbol} is undefined. | ||
| 834 | Avoid. | ||
| 835 | For example, here are two similar functions. | ||
| 836 | Both use @code{and}, @var{symbol} and @code{guard}: | ||
| 837 | |||
| 838 | @example | ||
| 839 | @group | ||
| 840 | (defun square-double-digit-p/CLEAN (integer) | ||
| 841 | (pcase (* integer integer) | ||
| 842 | ((and n (guard (< 9 n 100))) (list 'yes n)) | ||
| 843 | (sorry (list 'no sorry)))) | ||
| 844 | |||
| 845 | (square-double-digit-p/CLEAN 9) @result{} (yes 81) | ||
| 846 | (square-double-digit-p/CLEAN 3) @result{} (no 9) | ||
| 847 | @end group | ||
| 848 | |||
| 849 | @group | ||
| 850 | (defun square-double-digit-p/MAYBE (integer) | ||
| 851 | (pcase (* integer integer) | ||
| 852 | ((and n (guard (< 9 (incf n) 100))) (list 'yes n)) | ||
| 853 | (sorry (list 'no sorry)))) | ||
| 854 | |||
| 855 | (square-double-digit-p/MAYBE 9) @result{} (yes 81) | ||
| 856 | (square-double-digit-p/MAYBE 3) @result{} (yes 9) ; @r{WRONG!} | ||
| 857 | @end group | ||
| 858 | @end example | ||
| 859 | |||
| 860 | @noindent | ||
| 861 | The difference is in @var{boolean-expression} in @code{guard}: | ||
| 862 | @code{CLEAN} references @code{n} simply and directly, | ||
| 863 | while @code{MAYBE} references @code{n} with a side-effect, | ||
| 864 | in the expression @code{(incf n)}. | ||
| 865 | When @code{integer} is 3, here's what happens: | ||
| 866 | |||
| 867 | @itemize | ||
| 868 | @item The first @code{n} binds it to @var{expval}, | ||
| 869 | i.e., the result of evaluating @code{(* 3 3)}, or 9. | ||
| 870 | |||
| 871 | @item @var{boolean-expression} is evaluated: | ||
| 872 | |||
| 873 | @example | ||
| 874 | @group | ||
| 875 | start: (< 9 (incf n) 100) | ||
| 876 | becomes: (< 9 (setq n (1+ n)) 100) | ||
| 877 | becomes: (< 9 (setq n (1+ 9)) 100) | ||
| 878 | @end group | ||
| 879 | @group | ||
| 880 | becomes: (< 9 (setq n 10) 100) | ||
| 881 | ; @r{side-effect here!} | ||
| 882 | becomes: (< 9 n 100) ; @r{@code{n} now bound to 10} | ||
| 883 | becomes: (< 9 10 100) | ||
| 884 | becomes: t | ||
| 885 | @end group | ||
| 886 | @end example | ||
| 887 | |||
| 888 | @item Because the result of the evaluation is non-@code{nil}, | ||
| 889 | @code{guard} matches, @code{and} matches, and | ||
| 890 | control passes to that clause's body forms. | ||
| 891 | @end itemize | ||
| 892 | |||
| 893 | @noindent | ||
| 894 | Aside from the mathematical incorrectness of asserting that 9 is a | ||
| 895 | double-digit integer, there is another problem with @code{MAYBE}. | ||
| 896 | The body form references @code{n} once more, yet we do not see | ||
| 897 | the updated value---10---at all. What happened to it? | ||
| 898 | |||
| 899 | To sum up, it's best to avoid side-effecting references to | ||
| 900 | @var{symbol} patterns entirely, not only | ||
| 901 | in @var{boolean-expression} (in @code{guard}), | ||
| 902 | but also in @var{expr} (in @code{let}) | ||
| 903 | and @var{function} (in @code{pred} and @code{app}). | ||
| 904 | |||
| 905 | @item On match, the clause's body forms can reference the set | ||
| 906 | of symbols the pattern let-binds. | ||
| 907 | When @var{seqpat} is @code{and}, this set is | ||
| 908 | the union of all the symbols each of its sub-patterns let-binds. | ||
| 909 | This makes sense because, for @code{and} to match, | ||
| 910 | all the sub-patterns must match. | ||
| 911 | |||
| 912 | When @var{seqpat} is @code{or}, things are different: | ||
| 913 | @code{or} matches at the first sub-pattern that matches; | ||
| 914 | the rest of the sub-patterns are ignored. | ||
| 915 | It makes no sense for each sub-pattern to let-bind a different | ||
| 916 | set of symbols because the body forms have no way to distinguish | ||
| 917 | which sub-pattern matched and choose among the different sets. | ||
| 918 | For example, the following is invalid: | ||
| 919 | |||
| 920 | @example | ||
| 921 | @group | ||
| 922 | (pcase (read-number "Enter an integer: ") | ||
| 923 | ((or (and (pred evenp) | ||
| 924 | e-num) ; @r{bind @code{e-num} to @var{expval}} | ||
| 925 | o-num) ; @r{bind @code{o-num} to @var{expval}} | ||
| 926 | (list e-num o-num))) | ||
| 927 | @end group | ||
| 928 | |||
| 929 | @group | ||
| 930 | Enter an integer: 42 | ||
| 931 | @error{} Symbol’s value as variable is void: o-num | ||
| 932 | @end group | ||
| 933 | @group | ||
| 934 | Enter an integer: 149 | ||
| 935 | @error{} Symbol’s value as variable is void: e-num | ||
| 936 | @end group | ||
| 937 | @end example | ||
| 938 | |||
| 939 | @noindent | ||
| 940 | Evaluating body form @w{@code{(list e-num o-num)}} signals error. | ||
| 941 | To distinguish between sub-patterns, you can use another symbol, | ||
| 942 | identical in name in all sub-patterns but differing in value. | ||
| 943 | Reworking the above example: | ||
| 944 | |||
| 945 | @example | ||
| 946 | @group | ||
| 947 | (pcase (read-number "Enter an integer: ") | ||
| 948 | ((and num ; @r{line 1} | ||
| 949 | (or (and (pred evenp) ; @r{line 2} | ||
| 950 | (let spin 'even)) ; @r{line 3} | ||
| 951 | (let spin 'odd))) ; @r{line 4} | ||
| 952 | (list spin num))) ; @r{line 5} | ||
| 953 | @end group | ||
| 954 | |||
| 955 | @group | ||
| 956 | Enter an integer: 42 | ||
| 957 | @result{} (even 42) | ||
| 958 | @end group | ||
| 959 | @group | ||
| 960 | Enter an integer: 149 | ||
| 961 | @result{} (odd 149) | ||
| 962 | @end group | ||
| 963 | @end example | ||
| 964 | |||
| 965 | @noindent | ||
| 966 | Line 1 ``factors out'' the @var{expval} binding with | ||
| 967 | @code{and} and @var{symbol} (in this case, @code{num}). | ||
| 968 | On line 2, @code{or} begins in the same way as before, | ||
| 969 | but instead of binding different symbols, uses @code{let} twice | ||
| 970 | (lines 3-4) to bind the same symbol @code{spin} in both sub-patterns. | ||
| 971 | The value of @code{spin} distinguishes the sub-patterns. | ||
| 972 | The body form references both symbols (line 5). | ||
| 973 | @end enumerate | ||
| 974 | |||
| 975 | @node Extending pcase | ||
| 976 | @subsection Extending @code{pcase} | ||
| 977 | @cindex pcase, defining new kinds of patterns | ||
| 978 | |||
| 979 | The @code{pcase} macro supports several kinds of patterns | ||
| 980 | (@pxref{Pattern-Matching Conditional}). | ||
| 981 | You can add support for other kinds of patterns | ||
| 982 | using the @code{pcase-defmacro} macro. | ||
| 983 | |||
| 984 | @defmac pcase-defmacro name args [doc] &rest body | ||
| 985 | Define a new kind of pattern for @code{pcase}, to be invoked | ||
| 986 | as @w{@code{(@var{name} @var{actual-args})}}. | ||
| 987 | The @code{pcase} macro expands this into a function call | ||
| 988 | that evaluates @var{body}, whose job it is to | ||
| 989 | rewrite the invoked pattern into some other pattern, | ||
| 990 | in an environment where @var{args} are bound to @var{actual-args}. | ||
| 991 | |||
| 992 | Additionally, arrange to display @var{doc} along with | ||
| 993 | the docstring of @code{pcase}. | ||
| 994 | By convention, @var{doc} should use @code{EXPVAL} | ||
| 995 | to stand for the result of | ||
| 996 | evaluating @var{expression} (first arg to @code{pcase}). | ||
| 997 | @end defmac | ||
| 998 | |||
| 999 | @noindent | ||
| 1000 | Typically, @var{body} rewrites the invoked pattern | ||
| 1001 | to use more basic patterns. | ||
| 1002 | Although all patterns eventually reduce to core patterns, | ||
| 1003 | @code{body} need not use core patterns straight away. | ||
| 1004 | The following example defines two patterns, named | ||
| 1005 | @code{less-than} and @code{integer-less-than}. | ||
| 1006 | |||
| 1007 | @example | ||
| 1008 | @group | ||
| 1009 | (pcase-defmacro less-than (n) | ||
| 1010 | "Matches if EXPVAL is a number less than N." | ||
| 1011 | `(pred (> ,n))) | ||
| 1012 | @end group | ||
| 1013 | |||
| 1014 | @group | ||
| 1015 | (pcase-defmacro integer-less-than (n) | ||
| 1016 | "Matches if EXPVAL is an integer less than N." | ||
| 1017 | `(and (pred integerp) | ||
| 1018 | (less-than ,n))) | ||
| 1019 | @end group | ||
| 1020 | @end example | ||
| 1021 | |||
| 1022 | @noindent | ||
| 1023 | Note that the docstrings mention @var{args} | ||
| 1024 | (in this case, only one: @code{n}) in the usual way, | ||
| 1025 | and also mention @code{EXPVAL} by convention. | ||
| 1026 | The first rewrite (i.e., @var{body} for @code{less-than}) | ||
| 1027 | uses one core pattern: @code{pred}. | ||
| 1028 | The second uses two core patterns: @code{and} and @code{pred}, | ||
| 1029 | as well as the newly-defined pattern @code{less-than}. | ||
| 1030 | Both use a single backquote construct (@pxref{Backquote}). | ||
| 1031 | |||
| 1032 | @node Backquote Patterns | ||
| 1033 | @subsection Backquote-Style Patterns | ||
| 1034 | @cindex backquote-style patterns | ||
| 1035 | @cindex matching, structural | ||
| 1036 | @cindex structural matching | ||
| 1037 | |||
| 1038 | This subsection describes @dfn{backquote-style patterns}, | ||
| 1039 | a set of builtin patterns that eases structural matching. | ||
| 1040 | For background, @xref{Pattern-Matching Conditional}. | ||
| 1041 | |||
| 1042 | @dfn{Backquote-style patterns} are a powerful set of | ||
| 1043 | @code{pcase} pattern extensions (created using @code{pcase-defmacro}) | ||
| 1044 | that make it easy to match @var{expval} against | ||
| 1045 | specifications of its @emph{structure}. | ||
| 1046 | |||
| 1047 | For example, to match @var{expval} that must be a list of two | ||
| 1048 | elements whose first element is a specific string and the second | ||
| 1049 | element is any value, you can write a core pattern: | ||
| 1050 | |||
| 1051 | @example | ||
| 1052 | @group | ||
| 1053 | (and (pred listp) | ||
| 1054 | ls | ||
| 1055 | @end group | ||
| 1056 | @group | ||
| 1057 | (guard (= 2 (length ls))) | ||
| 1058 | (guard (string= "first" (car ls))) | ||
| 1059 | (let second-elem (cadr ls))) | ||
| 1060 | @end group | ||
| 1061 | @end example | ||
| 1062 | |||
| 1063 | @noindent | ||
| 1064 | or you can write the equivalent backquote-style pattern: | ||
| 1065 | |||
| 1066 | @example | ||
| 1067 | `("first" ,second-elem) | ||
| 1068 | @end example | ||
| 1069 | |||
| 1070 | @noindent | ||
| 1071 | The backquote-style pattern is more concise, | ||
| 1072 | resembles the structure of @var{expval}, | ||
| 1073 | and avoids binding @code{ls}. | ||
| 1074 | |||
| 1075 | A backquote-style pattern has the form @code{`@var{qpat}} where | ||
| 1076 | @var{qpat} can have the following forms: | ||
| 1077 | |||
| 1078 | @table @code | ||
| 1079 | |||
| 1080 | @item (@var{qpat1} . @var{qpat2}) | ||
| 1081 | Matches if @var{expval} is a cons cell whose @code{car} | ||
| 1082 | matches @var{qpat1} and whose @code{cdr} matches @var{qpat2}. | ||
| 1083 | This readily generalizes to lists as in | ||
| 1084 | @w{@code{(@var{qpat1} @var{qpat2} @dots{})}}. | ||
| 1085 | |||
| 1086 | @item [@var{qpat1} @var{qpat2} @dots{} @var{qpatm}] | ||
| 1087 | Matches if @var{expval} is a vector of length @var{m} whose | ||
| 1088 | @code{0}..@code{(@var{m}-1)}th elements match @var{qpat1}, | ||
| 1089 | @var{qpat2} @dots{} @var{qpatm}, respectively. | ||
| 1090 | |||
| 1091 | @item @var{symbol} | ||
| 1092 | @itemx @var{keyword} | ||
| 1093 | @itemx @var{integer} | ||
| 1094 | @itemx @var{string} | ||
| 1095 | Matches if the corresponding element of @var{expval} is | ||
| 1096 | @code{equal} to the specified literal object. | ||
| 1097 | Note that, aside from @var{symbol}, this is the same set of | ||
| 1098 | self-quoting literal objects that are acceptable as a core pattern. | ||
| 1099 | |||
| 1100 | @item ,@var{pattern} | ||
| 1101 | Matches if the corresponding element of @var{expval} | ||
| 1102 | matches @var{pattern}. | ||
| 1103 | Note that @var{pattern} is any kind that @code{pcase} supports. | ||
| 1104 | (In the example above, @code{second-elem} is a @var{symbol} | ||
| 1105 | core pattern; it therefore matches anything, | ||
| 1106 | and let-binds @code{second-elem}.) | ||
| 1107 | @end table | ||
| 1108 | |||
| 1109 | The @dfn{corresponding element} is the portion of @var{expval} | ||
| 1110 | that is in the same structural position as the structural position | ||
| 1111 | of @var{qpat} in the backquote-style pattern. | ||
| 1112 | (In the example above, the corresponding element of | ||
| 1113 | @code{second-elem} is the second element of @var{expval}.) | ||
| 1114 | |||
| 1115 | Here is an example of using @code{pcase} to implement a simple | ||
| 1116 | interpreter for a little expression language | ||
| 1117 | (note that this requires lexical binding for the | ||
| 1118 | lambda expression in the @code{fn} clause to properly | ||
| 1119 | capture @code{body} and @code{arg} (@pxref{Lexical Binding}): | ||
| 1120 | |||
| 1121 | @example | ||
| 1122 | @group | ||
| 1123 | (defun evaluate (form env) | ||
| 1124 | (pcase form | ||
| 1125 | (`(add ,x ,y) (+ (evaluate x env) | ||
| 1126 | (evaluate y env))) | ||
| 1127 | @end group | ||
| 1128 | @group | ||
| 1129 | (`(call ,fun ,arg) (funcall (evaluate fun env) | ||
| 1130 | (evaluate arg env))) | ||
| 1131 | (`(fn ,arg ,body) (lambda (val) | ||
| 1132 | (evaluate body (cons (cons arg val) | ||
| 1133 | env)))) | ||
| 1134 | @end group | ||
| 1135 | @group | ||
| 1136 | ((pred numberp) form) | ||
| 1137 | ((pred symbolp) (cdr (assq form env))) | ||
| 1138 | (_ (error "Syntax error: %S" form)))) | ||
| 1139 | @end group | ||
| 1140 | @end example | ||
| 1141 | |||
| 1142 | @noindent | ||
| 1143 | The first three clauses use backquote-style patterns. | ||
| 1144 | @code{`(add ,x ,y)} is a pattern that checks that @code{form} | ||
| 1145 | is a three-element list starting with the literal symbol @code{add}, | ||
| 1146 | then extracts the second and third elements and binds them | ||
| 1147 | to symbols @code{x} and @code{y}, respectively. | ||
| 1148 | The clause body evaluates @code{x} and @code{y} and adds the results. | ||
| 1149 | Similarly, the @code{call} clause implements a function call, | ||
| 1150 | and the @code{fn} clause implements an anonymous function definition. | ||
| 1151 | |||
| 1152 | The remaining clauses use core patterns. | ||
| 1153 | @code{(pred numberp)} matches if @code{form} is a number. | ||
| 1154 | On match, the body evaluates it. | ||
| 1155 | @code{(pred symbolp)} matches if @code{form} is a symbol. | ||
| 1156 | On match, the body looks up the symbol in @code{env} and | ||
| 1157 | returns its association. | ||
| 1158 | Finally, @code{_} is the catch-all pattern that | ||
| 1159 | matches anything, so it's suitable for reporting syntax errors. | ||
| 1160 | |||
| 1161 | Here are some sample programs in this small language, including their | ||
| 1162 | evaluation results: | ||
| 1163 | |||
| 1164 | @example | ||
| 1165 | (evaluate '(add 1 2) nil) @result{} 3 | ||
| 1166 | (evaluate '(add x y) '((x . 1) (y . 2))) @result{} 3 | ||
| 1167 | (evaluate '(call (fn x (add 1 x)) 2) nil) @result{} 3 | ||
| 1168 | (evaluate '(sub 1 2) nil) @result{} error | ||
| 1169 | @end example | ||
| 1170 | |||
| 624 | @node Iteration | 1171 | @node Iteration |
| 625 | @section Iteration | 1172 | @section Iteration |
| 626 | @cindex iteration | 1173 | @cindex iteration |
diff --git a/doc/lispref/elisp.texi b/doc/lispref/elisp.texi index 9389aa1ba19..7ac9198bf84 100644 --- a/doc/lispref/elisp.texi +++ b/doc/lispref/elisp.texi | |||
| @@ -476,14 +476,11 @@ Control Structures | |||
| 476 | * Sequencing:: Evaluation in textual order. | 476 | * Sequencing:: Evaluation in textual order. |
| 477 | * Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}. | 477 | * Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}. |
| 478 | * Combining Conditions:: @code{and}, @code{or}, @code{not}. | 478 | * Combining Conditions:: @code{and}, @code{or}, @code{not}. |
| 479 | * Pattern-Matching Conditional:: How to use @code{pcase} and friends. | ||
| 479 | * Iteration:: @code{while} loops. | 480 | * Iteration:: @code{while} loops. |
| 480 | * Generators:: Generic sequences and coroutines. | 481 | * Generators:: Generic sequences and coroutines. |
| 481 | * Nonlocal Exits:: Jumping out of a sequence. | 482 | * Nonlocal Exits:: Jumping out of a sequence. |
| 482 | 483 | ||
| 483 | Conditionals | ||
| 484 | |||
| 485 | * Pattern matching case statement:: How to use @code{pcase}. | ||
| 486 | |||
| 487 | Nonlocal Exits | 484 | Nonlocal Exits |
| 488 | 485 | ||
| 489 | * Catch and Throw:: Nonlocal exits for the program's own purposes. | 486 | * Catch and Throw:: Nonlocal exits for the program's own purposes. |