aboutsummaryrefslogtreecommitdiffstats
path: root/doc
diff options
context:
space:
mode:
authorMichael Albinus2018-05-29 10:07:21 +0200
committerMichael Albinus2018-05-29 10:07:21 +0200
commit8a09ec0d45cdc8fa54203a0f7cc1a8c909627497 (patch)
tree2b7516e767bea0d86e3f819b6856841083f138b9 /doc
parent0f48d18fd2a30f29cc3592a835d2a2254c9b0afb (diff)
parent9d6a3ac73af66184e5bb23555b93833f6a4d9f2e (diff)
downloademacs-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.texi967
-rw-r--r--doc/lispref/elisp.texi5
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
150has four conditional forms: @code{if}, which is much the same as in 151has five conditional forms: @code{if}, which is much the same as in
151other languages; @code{when} and @code{unless}, which are variants of 152other 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;
154and @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
300The @code{cond} form lets you choose between alternatives using
301predicate conditions that compare values of expressions against
302specific values known and written in advance. However, sometimes it
303is useful to select alternatives based on more general conditions that
304distinguish between broad classes of values. The @code{pcase} macro
305allows you to choose between alternatives based on matching the value
306of an expression against a series of patterns. A pattern can be a
307literal value (for comparisons to literal values you'd use
308@code{cond}), or it can be a more general description of the expected
309structure of the expression's value.
310
311@defmac pcase expression &rest clauses
312Evaluate @var{expression} and choose among an arbitrary number of
313alternatives based on the value of @var{expression}. The possible
314alternatives are specified by @var{clauses}, each of which must be a
315list 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,
318the clause succeeds; @code{pcase} then evaluates its @var{body-forms},
319and 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}
321form evaluates to @code{nil}.
322
323The @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
326describe them first.
327
328Note: In the description of the patterns below, we use ``the value
329being matched'' to refer to the value of the @var{expression} that is
330the first argument of @code{pcase}.
331
332A UPattern can have the following forms:
333
334@table @code
335
336@item '@var{val}
337Matches if the value being matched is @code{equal} to @var{val}.
338@item @var{atom}
339Matches 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
341shorthand for @code{'@var{atom}}.) Note that a string or a float
342matches any string or float with the same contents/value.
343@item _
344Matches any value. This is known as @dfn{don't care} or @dfn{wildcard}.
345@item @var{symbol}
346Matches any value, and additionally let-binds @var{symbol} to the
347value 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})
350Matches if the predicate function @var{predfun} returns non-@code{nil}
351when 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})
354Matches if @var{boolean-expression} evaluates to non-@code{nil}. This
355allows you to include in a UPattern boolean conditions that refer to
356symbols bound to values (including the value being matched) by
357previous UPatterns. Typically used inside an @code{and} UPattern, see
358below. For example, @w{@code{(and x (guard (< x 10)))}} is a pattern
359which matches any number smaller than 10 and let-binds the variable
360@code{x} to that number.
361@item (let @var{upattern} @var{expression})
362Matches if the specified @var{expression} matches the specified
363@var{upattern}. This allows matching a pattern against the value of
364an @emph{arbitrary} expression, not just the expression that is the
365first argument to @code{pcase}. (It is called @code{let} because
366@var{upattern} can bind symbols to values using the @var{symbol}
367UPattern. For example:
368@w{@code{((or `(key . ,val) (let val 5)) val)}}.)
369@item (app @var{function} @var{upattern})
370Matches if @var{function} applied to the value being matched returns a
371value that matches @var{upattern}. This is like the @code{pred}
372UPattern, except that it tests the result against @var{upattern},
373rather than against a boolean truth value. The @var{function} call can
374use one of the forms described below.
375@item (or @var{upattern1} @var{upattern2}@dots{})
376Matches if one the argument UPatterns matches. As soon as the first
377matching UPattern is found, the rest are not tested. For this reason,
378if any of the UPatterns let-bind symbols to the matched value, they
379should all bind the same symbols.
380@item (and @var{upattern1} @var{upattern2}@dots{})
381Matches if all the argument UPatterns match.
382@end table
383
384The function calls used in the @code{pred} and @code{app} UPatterns
385can have one of the following forms:
386
387@table @asis
388@item function symbol, like @code{integerp}
389In this case, the named function is applied to the value being
390matched.
391@item lambda-function @code{(lambda (@var{arg}) @var{body})}
392In this case, the lambda-function is called with one argument, the
393value being matched.
394@item @code{(@var{func} @var{args}@dots{})}
395This is a function call with @var{n} specified arguments; the function
396is called with these @var{n} arguments and an additional @var{n}+1-th
397argument that is the value being matched.
398@end table
399
400Here'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
413In addition, you can use backquoted patterns that are more powerful.
414They allow matching the value of the @var{expression} that is the
415first argument of @code{pcase} against specifications of its
416@emph{structure}. For example, you can specify that the value must be
417a list of 2 elements whose first element is a specific string and the
418second element is any value with a backquoted pattern like
419@code{`("first" ,second-elem)}.
420
421Backquoted 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})
426Matches if the value being matched is a cons cell whose @code{car}
427matches @var{qpattern1} and whose @code{cdr} matches @var{qpattern2}.
428This readily generalizes to backquoted lists as in
429@w{@code{(@var{qpattern1} @var{qpattern2} @dots{})}}.
430@item [@var{qpattern1} @var{qpattern2} @dots{} @var{qpatternm}]
431Matches 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}
435Matches if corresponding element of the value being matched is
436@code{equal} to the specified @var{atom}.
437@item ,@var{upattern}
438Matches if the corresponding element of the value being matched
439matches the specified @var{upattern}.
440@end table
441
442Note that uses of QPatterns can be expressed using only UPatterns, as
443QPatterns are implemented on top of UPatterns using
444@code{pcase-defmacro}, described below. However, using QPatterns will
445in 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
451Here is an example of using @code{pcase} to implement a simple
452interpreter for a little expression language (note that this example
453requires 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
467Here @code{`(add ,x ,y)} is a pattern that checks that @code{exp} is a
468three-element list starting with the literal symbol @code{add}, then
469extracts 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
471adds the results. The @code{call} and @code{fn} patterns similarly
472implement two flavors of function calls. @code{(pred numberp)} is a
473pattern that simply checks that @code{exp} is a number and if so,
474evaluates it. @code{(pred symbolp)} matches symbols, and returns
475their association. Finally, @code{_} is the catch-all pattern that
476matches anything, so it's suitable for reporting syntax errors.
477
478Here are some sample programs in this small language, including their
479evaluation 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
488Additional UPatterns can be defined using the @code{pcase-defmacro}
489macro.
490
491@defmac pcase-defmacro name args &rest body
492Define a new kind of UPattern for @code{pcase}. The new UPattern will
493be invoked as @code{(@var{name} @var{actual-args})}. The @var{body}
494should describe how to rewrite the UPattern @var{name} into some other
495UPattern. The rewriting will be the result of evaluating @var{body}
496in 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
424Aside from the four basic conditional forms, Emacs Lisp also
425has a pattern-matching conditional form, the @code{pcase} macro,
426a hybrid of @code{cond} and @code{cl-case}
427(@pxref{Conditionals,,,cl,Common Lisp Extensions})
428that overcomes their limitations and introduces
429the @dfn{pattern matching} programming style.
430First, the limitations:
431
432@itemize
433@item The @code{cond} form chooses among alternatives
434by evaluating the predicate @var{condition} of each
435of its clauses (@pxref{Conditionals}).
436The primary limitation is that variables let-bound in @var{condition}
437are not available to the clause's @var{body-forms}.
438
439Another annoyance (more an inconvenience than a limitation)
440is that when a series of @var{condition} predicates implement
441equality tests, there is a lot of repeated code.
442For that, why not use @code{cl-case}?
443
444@item
445The @code{cl-case} macro chooses among alternatives by evaluating
446the equality of its first argument against a set of specific
447values.
448The 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
456These render @code{cl-case} unsuitable for strings or compound
457data structures (e.g., lists or vectors).
458For that, why not use @code{cond}?
459(And here we end up in a circle.)
460@end itemize
461
462@noindent
463Conceptually, the @code{pcase} macro borrows the first-arg focus
464of @code{cl-case} and the clause-processing flow of @code{cond},
465replacing @var{condition} with a generalization of
466the equality test called @dfn{matching},
467and adding facilities so that you can concisely express a
468clause's predicate, and arrange to share let-bindings between
469a clause's predicate and @var{body-forms}.
470
471The concise expression of a predicate is known as a @dfn{pattern}.
472When the predicate, called on the value of the first arg,
473returns 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
485For background, @xref{Pattern-Matching Conditional}.
486
487@defmac pcase expression &rest clauses
488Each clause in @var{clauses} has the form:
489@w{@code{(@var{pattern} @var{body-forms}@dots{})}}.
490
491Evaluate @var{expression} to determine its value, @var{expval}.
492Find the first clause in @var{clauses} whose @var{pattern} matches
493@var{expval} and pass control to that clause's @var{body-forms}.
494
495If there is a match, the value of @code{pcase} is the value
496of the last of @var{body-forms} in the successful clause.
497Otherwise, @code{pcase} evaluates to @code{nil}.
498@end defmac
499
500The rest of this subsection
501describes different forms of core patterns,
502presents some examples,
503and concludes with important caveats on using the
504let-binding facility provided by some pattern forms.
505A core pattern can have the following forms:
506
507@table @code
508
509@item _
510Matches any @var{expval}.
511This is known as @dfn{don't care} or @dfn{wildcard}.
512
513@item '@var{val}
514Matches if @var{expval} is @code{equal} to @var{val}.
515
516@item @var{keyword}
517@itemx @var{integer}
518@itemx @var{string}
519Matches if @var{expval} is @code{equal} to the literal object.
520This is a special case of @code{'@var{val}}, above,
521possible because literal objects of these types are self-quoting.
522
523@item @var{symbol}
524Matches 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
528If @var{symbol} is part of a sequencing pattern @var{seqpat}
529(e.g., by using @code{and}, below), the binding is also available to
530the portion of @var{seqpat} following the appearance of @var{symbol}.
531This usage has some caveats (@pxref{pcase-symbol-caveats,,caveats}).
532
533Two symbols to avoid are @code{t}, which behaves like @code{_}
534(above) and is deprecated, and @code{nil}, which signals error.
535Likewise, it makes no sense to bind keyword symbols
536(@pxref{Constant Variables}).
537
538@item (pred @var{function})
539Matches if the predicate @var{function} returns non-@code{nil}
540when called on @var{expval}.
541@var{function} can have one of the possible forms:
542
543@table @asis
544@item function name (a symbol)
545Call the named function with one argument, @var{expval}.
546
547Example: @code{integerp}
548
549@item lambda expression
550Call the anonymous function with one argument,
551@var{expval} (@pxref{Lambda Expressions}).
552
553Example: @code{(lambda (n) (= 42 n))}
554
555@item function call with @var{n} args
556Call the function (the first element of the function call)
557with @var{n} arguments (the other elements) and an additional
558@var{n}+1-th argument that is @var{expval}.
559
560Example: @code{(= 42)}@*
561In this example, the function is @code{=}, @var{n} is one, and
562the actual function call becomes: @w{@code{(= 42 @var{expval})}}.
563@end table
564
565@item (app @var{function} @var{pattern})
566Matches if @var{function} called on @var{expval} returns a
567value that matches @var{pattern}.
568@var{function} can take one of the
569forms described for @code{pred}, above.
570Unlike @code{pred}, however,
571@code{app} tests the result against @var{pattern},
572rather than against a boolean truth value.
573
574@item (guard @var{boolean-expression})
575Matches if @var{boolean-expression} evaluates to non-@code{nil}.
576
577@item (let @var{pattern} @var{expr})
578Evaluates @var{expr} to get @var{exprval}
579and 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
585A @dfn{sequencing pattern} (also known as @var{seqpat}) is a
586pattern that processes its sub-pattern arguments in sequence.
587There are two for @code{pcase}: @code{and} and @code{or}.
588They behave in a similar manner to the special forms
589that share their name (@pxref{Combining Conditions}),
590but instead of processing values, they process sub-patterns.
591
592@table @code
593@item (and @var{pattern1}@dots{})
594Attempts to match @var{pattern1}@dots{}, in order,
595until one of them fails to match.
596In that case, @code{and} likewise fails to match,
597and the rest of the sub-patterns are not tested.
598If all sub-patterns match, @code{and} matches.
599
600@item (or @var{pattern1} @var{pattern2}@dots{})
601Attempts to match @var{pattern1}, @var{pattern2}, @dots{}, in order,
602until one of them succeeds.
603In that case, @code{or} likewise matches,
604and the rest of the sub-patterns are not tested.
605(Note that there must be at least two sub-patterns.
606Simply @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
611To present a consistent environment (@pxref{Intro Eval})
612to @var{body-forms} (thus avoiding an evaluation error on match),
613if any of the sub-patterns let-binds a set of symbols,
614they @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
620Here's an example that highlights some advantages @code{pcase}
621has 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
645With @code{cl-case}, you would need to explicitly declare a local
646variable @code{code} to hold the return value of @code{get-return-code}.
647Also @code{cl-case} is difficult to use with strings because it
648uses @code{eql} for comparison.
649
650@anchor{pcase-example-1}
651@subheading Example: Using @code{and}
652
653A common idiom is to write a pattern starting with @code{and},
654with one or more @var{symbol} sub-patterns providing bindings
655to the sub-patterns that follow (as well as to the body forms).
656For 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
668First, @code{pred} matches if @w{@code{(integerp @var{expval})}}
669evaluates to non-@code{nil}.
670Next, @code{n} is a @var{symbol} pattern that matches
671anything and binds @code{n} to @var{expval}.
672Lastly, @code{guard} matches if the boolean expression
673@w{@code{(<= -9 n 9)}} (note the reference to @code{n})
674evaluates to non-@code{nil}.
675If all these sub-patterns match, @code{and} matches.
676
677@anchor{pcase-example-2}
678@subheading Example: Reformulation with @code{pcase}
679
680Here is another example that shows how to reformulate a simple
681matching task from its traditional implementation
682(function @code{grok/traditional}) to one using
683@code{pcase} (function @code{grok/pcase}).
684The 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).''
687First, 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
706The 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
732The bulk of @code{grok/pcase} is a single clause of a @code{pcase}
733form, the pattern on lines 1-8, the (single) body form on line 9.
734The pattern is @code{or}, which tries to match in turn its argument
735sub-patterns, first @code{and} (lines 2-7), then @code{let} (line 8),
736until one of them succeeds.
737
738As in the previous example (@pxref{pcase-example-1,,Example 1}),
739@code{and} begins with a @code{pred} sub-pattern to ensure
740the following sub-patterns work with an object of the correct
741type (string, in this case). If @w{@code{(stringp @var{expval})}}
742returns @code{nil}, @code{pred} fails, and thus @code{and} fails, too.
743
744The next @code{pred} (lines 4-5) evaluates
745@w{@code{(string-match RX @var{expval})}}
746and matches if the result is non-@code{nil}, which means
747that @var{expval} has the desired form: @code{key:NUMBER}.
748Again, failing this, @code{pred} fails and @code{and}, too.
749
750Lastly (in this series of @code{and} sub-patterns), @code{app}
751evaluates @w{@code{(match-string 1 @var{expval})}} (line 6)
752to get a temporary value @var{tmp} (i.e., the ``NUMBER'' substring)
753and tries to match @var{tmp} against pattern @code{val} (line 7).
754Since that is a @var{symbol} pattern, it matches unconditionally
755and additionally binds @code{val} to @var{tmp}.
756
757Now that @code{app} has matched, all @code{and} sub-patterns
758have matched, and so @code{and} matches.
759Likewise, once @code{and} has matched, @code{or} matches
760and does not proceed to try sub-pattern @code{let} (line 8).
761
762Let's consider the situation where @code{obj} is not a string,
763or it is a string but has the wrong form.
764In this case, one of the @code{pred} (lines 3-5) fails to match,
765thus @code{and} (line 2) fails to match,
766thus @code{or} (line 1) proceeds to try sub-pattern @code{let} (line 8).
767
768First, @code{let} evaluates @w{@code{(list "149" 'default)}}
769to get @w{@code{("149" default)}}, the @var{exprval}, and then
770tries to match @var{exprval} against pattern @code{val}.
771Since that is a @var{symbol} pattern, it matches unconditionally
772and additionally binds @code{val} to @var{exprval}.
773Now that @code{let} has matched, @code{or} matches.
774
775Note how both @code{and} and @code{let} sub-patterns finish in the
776same way: by trying (always successfully) to match against the
777@var{symbol} pattern @code{val}, in the process binding @code{val}.
778Thus, @code{or} always matches and control always passes
779to the body form (line 9).
780Because that is the last body form in a successfully matched
781@code{pcase} clause, it is the value of @code{pcase} and likewise
782the 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
787The preceding examples all use sequencing patterns
788which include the @var{symbol}
789sub-pattern in some way.
790Here are some important details about that usage.
791
792@enumerate
793@item When @var{symbol} occurs more than once in @var{seqpat},
794the second and subsequent occurances do not expand to re-binding,
795but instead expand to an equality test using @code{eq}.
796
797The following example features a @code{pcase} form
798with two clauses and two @var{seqpat}, A and B.
799Both A and B first check that @var{expval} is a
800pair (using @code{pred}),
801and then bind symbols to the @code{car} and @code{cdr}
802of @var{expval} (using one @code{app} each).
803
804For A, because symbol @code{st} is mentioned twice, the second
805mention becomes an equality test using @code{eq}.
806On 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.
834Avoid.
835For example, here are two similar functions.
836Both 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
861The difference is in @var{boolean-expression} in @code{guard}:
862@code{CLEAN} references @code{n} simply and directly,
863while @code{MAYBE} references @code{n} with a side-effect,
864in the expression @code{(incf n)}.
865When @code{integer} is 3, here's what happens:
866
867@itemize
868@item The first @code{n} binds it to @var{expval},
869i.e., the result of evaluating @code{(* 3 3)}, or 9.
870
871@item @var{boolean-expression} is evaluated:
872
873@example
874@group
875start: (< 9 (incf n) 100)
876becomes: (< 9 (setq n (1+ n)) 100)
877becomes: (< 9 (setq n (1+ 9)) 100)
878@end group
879@group
880becomes: (< 9 (setq n 10) 100)
881 ; @r{side-effect here!}
882becomes: (< 9 n 100) ; @r{@code{n} now bound to 10}
883becomes: (< 9 10 100)
884becomes: 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
890control passes to that clause's body forms.
891@end itemize
892
893@noindent
894Aside from the mathematical incorrectness of asserting that 9 is a
895double-digit integer, there is another problem with @code{MAYBE}.
896The body form references @code{n} once more, yet we do not see
897the updated value---10---at all. What happened to it?
898
899To sum up, it's best to avoid side-effecting references to
900@var{symbol} patterns entirely, not only
901in @var{boolean-expression} (in @code{guard}),
902but also in @var{expr} (in @code{let})
903and @var{function} (in @code{pred} and @code{app}).
904
905@item On match, the clause's body forms can reference the set
906of symbols the pattern let-binds.
907When @var{seqpat} is @code{and}, this set is
908the union of all the symbols each of its sub-patterns let-binds.
909This makes sense because, for @code{and} to match,
910all the sub-patterns must match.
911
912When @var{seqpat} is @code{or}, things are different:
913@code{or} matches at the first sub-pattern that matches;
914the rest of the sub-patterns are ignored.
915It makes no sense for each sub-pattern to let-bind a different
916set of symbols because the body forms have no way to distinguish
917which sub-pattern matched and choose among the different sets.
918For 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
930Enter an integer: 42
931@error{} Symbol’s value as variable is void: o-num
932@end group
933@group
934Enter an integer: 149
935@error{} Symbol’s value as variable is void: e-num
936@end group
937@end example
938
939@noindent
940Evaluating body form @w{@code{(list e-num o-num)}} signals error.
941To distinguish between sub-patterns, you can use another symbol,
942identical in name in all sub-patterns but differing in value.
943Reworking 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
956Enter an integer: 42
957@result{} (even 42)
958@end group
959@group
960Enter an integer: 149
961@result{} (odd 149)
962@end group
963@end example
964
965@noindent
966Line 1 ``factors out'' the @var{expval} binding with
967@code{and} and @var{symbol} (in this case, @code{num}).
968On line 2, @code{or} begins in the same way as before,
969but instead of binding different symbols, uses @code{let} twice
970(lines 3-4) to bind the same symbol @code{spin} in both sub-patterns.
971The value of @code{spin} distinguishes the sub-patterns.
972The 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
979The @code{pcase} macro supports several kinds of patterns
980(@pxref{Pattern-Matching Conditional}).
981You can add support for other kinds of patterns
982using the @code{pcase-defmacro} macro.
983
984@defmac pcase-defmacro name args [doc] &rest body
985Define a new kind of pattern for @code{pcase}, to be invoked
986as @w{@code{(@var{name} @var{actual-args})}}.
987The @code{pcase} macro expands this into a function call
988that evaluates @var{body}, whose job it is to
989rewrite the invoked pattern into some other pattern,
990in an environment where @var{args} are bound to @var{actual-args}.
991
992Additionally, arrange to display @var{doc} along with
993the docstring of @code{pcase}.
994By convention, @var{doc} should use @code{EXPVAL}
995to stand for the result of
996evaluating @var{expression} (first arg to @code{pcase}).
997@end defmac
998
999@noindent
1000Typically, @var{body} rewrites the invoked pattern
1001to use more basic patterns.
1002Although all patterns eventually reduce to core patterns,
1003@code{body} need not use core patterns straight away.
1004The 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
1023Note that the docstrings mention @var{args}
1024(in this case, only one: @code{n}) in the usual way,
1025and also mention @code{EXPVAL} by convention.
1026The first rewrite (i.e., @var{body} for @code{less-than})
1027uses one core pattern: @code{pred}.
1028The second uses two core patterns: @code{and} and @code{pred},
1029as well as the newly-defined pattern @code{less-than}.
1030Both 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
1038This subsection describes @dfn{backquote-style patterns},
1039a set of builtin patterns that eases structural matching.
1040For 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})
1044that make it easy to match @var{expval} against
1045specifications of its @emph{structure}.
1046
1047For example, to match @var{expval} that must be a list of two
1048elements whose first element is a specific string and the second
1049element 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
1064or you can write the equivalent backquote-style pattern:
1065
1066@example
1067`("first" ,second-elem)
1068@end example
1069
1070@noindent
1071The backquote-style pattern is more concise,
1072resembles the structure of @var{expval},
1073and avoids binding @code{ls}.
1074
1075A 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})
1081Matches if @var{expval} is a cons cell whose @code{car}
1082matches @var{qpat1} and whose @code{cdr} matches @var{qpat2}.
1083This readily generalizes to lists as in
1084@w{@code{(@var{qpat1} @var{qpat2} @dots{})}}.
1085
1086@item [@var{qpat1} @var{qpat2} @dots{} @var{qpatm}]
1087Matches 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}
1095Matches if the corresponding element of @var{expval} is
1096@code{equal} to the specified literal object.
1097Note that, aside from @var{symbol}, this is the same set of
1098self-quoting literal objects that are acceptable as a core pattern.
1099
1100@item ,@var{pattern}
1101Matches if the corresponding element of @var{expval}
1102matches @var{pattern}.
1103Note that @var{pattern} is any kind that @code{pcase} supports.
1104(In the example above, @code{second-elem} is a @var{symbol}
1105core pattern; it therefore matches anything,
1106and let-binds @code{second-elem}.)
1107@end table
1108
1109The @dfn{corresponding element} is the portion of @var{expval}
1110that is in the same structural position as the structural position
1111of @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
1115Here is an example of using @code{pcase} to implement a simple
1116interpreter for a little expression language
1117(note that this requires lexical binding for the
1118lambda expression in the @code{fn} clause to properly
1119capture @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
1143The first three clauses use backquote-style patterns.
1144@code{`(add ,x ,y)} is a pattern that checks that @code{form}
1145is a three-element list starting with the literal symbol @code{add},
1146then extracts the second and third elements and binds them
1147to symbols @code{x} and @code{y}, respectively.
1148The clause body evaluates @code{x} and @code{y} and adds the results.
1149Similarly, the @code{call} clause implements a function call,
1150and the @code{fn} clause implements an anonymous function definition.
1151
1152The remaining clauses use core patterns.
1153@code{(pred numberp)} matches if @code{form} is a number.
1154On match, the body evaluates it.
1155@code{(pred symbolp)} matches if @code{form} is a symbol.
1156On match, the body looks up the symbol in @code{env} and
1157returns its association.
1158Finally, @code{_} is the catch-all pattern that
1159matches anything, so it's suitable for reporting syntax errors.
1160
1161Here are some sample programs in this small language, including their
1162evaluation 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
483Conditionals
484
485* Pattern matching case statement:: How to use @code{pcase}.
486
487Nonlocal Exits 484Nonlocal 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.