-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontrol.texi
1634 lines (1379 loc) · 65 KB
/
control.texi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@c -*-texinfo-*-
@c This is part of the GNU Emacs Lisp Reference Manual.
@c Copyright (C) 1990-1995, 1998-1999, 2001-2015 Free Software
@c Foundation, Inc.
@c See the file elisp.texi for copying conditions.
@documentencoding UTF-8
@node Control Structures
@chapter 制御構造
@cindex 制御構造向けのスペシャルフォーム
@cindex 制御構造
Lispプログラムは、@dfn{式}、すなわち、@dfn{フォーム}(forms、
@pxref{Forms})から成ります。フォームを@dfn{制御構造}(control
structures)で囲むことで、フォームの実行順序を制御します。
制御構造はスペシャルフォームであり、その内側にあるフォームの実行をいつ行うか、
行わないか、何回行うかを制御します。
@cindex textual order
もっとも単純な実行順序は逐次実行です。
最初のフォーム@var{a}を実行し、それからつぎのフォーム@var{b}を実行し、といった具合です。
関数の本体やLispコードのファイルのトップレベルに複数のフォームを順に書くと、
このようになります。
つまり、書かれている順番にフォームを実行します。
これを@dfn{テキスト上の順序}(textual order)と呼びます。
たとえば、関数本体が2つのフォーム@var{a}と@var{b}から成る場合、
関数を評価すると、まず@var{a}を評価し、つぎに@var{b}を評価して、関数の値は@var{b}の値になります。
明示的な制御構造により、逐次実行以外の実行順序が可能になります。
Emacs Lispには数種類の制御構造があり、
逐次実行の変形、条件付き実行、繰り返し実行、
(制御された)ジャンプなどです。
これらすべては、以下に説明します。
組み込みの制御構造はスペシャルフォームです。
というのは、それらのサブフォームは必ずしも評価しませんし、
逐次評価するわけでもないからです。
マクロを使えば、独自の制御構造の構文を定義できます(@pxref{Macros})。
@menu
* Sequencing:: Evaluation in textual order.
* Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}.
* Combining Conditions:: @code{and}, @code{or}, @code{not}.
* Iteration:: @code{while} loops.
* Generators:: Generic sequences and coroutines.
* Nonlocal Exits:: Jumping out of a sequence.
@end menu
@node Sequencing
@section 逐次実行
@cindex 逐次実行
@cindex 逐次的な実行
現れる順番にフォームを評価することは、
1つのフォームから別のフォームへ制御を移すもっとも一般的な方法です。
関数本体などのある種の文脈では、自動的にこのようになります。
それ以外では、これを行う制御構造の構文を使う必要があります。
@code{progn}がその制御構造で、Lispのもっとも単純な制御構造です。
スペシャルフォーム@code{progn}はつぎのような形です。
@example
@group
(progn @var{a} @var{b} @var{c} @dots{})
@end group
@end example
@noindent
これは、フォーム、@var{a}、@var{b}、@var{c}、…をこの順に評価します。
これらのフォームを@code{progn}フォームの@dfn{本体}と呼びます。
本体の最後のフォームの値が、@code{progn}全体の値になります。
@code{(progn)} は @code{nil}を返します。
@cindex 暗黙の@code{progn}
初期のころのLispでは、@code{progn}は、
2つ以上のフォームを逐次実行しそれらの最後の値を使う唯一の方法でした。
しかし、プログラマは、(当時は)1つのフォームしか許されていない
関数の本体では、
@code{progn}を使う必要がしばしばあることに気づきました。
そのため、関数本体を『暗黙の@code{progn}』にしたのです。
つまり、実際の@code{progn}の本体のように、
複数のフォームを許すようにしたのです。
多くの他の制御構造も、同様に、暗黙の@code{progn}です。
その結果、@code{progn}は、かつてほどは多用されません。
現在では、@code{unwind-protect}、@code{and}、@code{or}の内側や、
@code{if}の@var{then}部分で必要とされるのがほとんどです。
@defspec progn forms@dots{}
このスペシャルフォームは、@var{forms}のフォームすべてを
テキスト上の順に評価し、最後のフォームの結果を返す。
@example
@group
(progn (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The third form"
@end group
@end example
@end defspec
他の2つの制御構造も同様にフォームを逐次評価しますが、
返す値が異なります。
@defspec prog1 form1 forms@dots{}
このスペシャルフォームは、@var{form1}、@var{forms}のフォームすべてを
テキスト上の順に評価し、@var{form1}の結果を返す。
@example
@group
(prog1 (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The first form"
@end group
@end example
変数@code{x}のリストから先頭要素を取り除き、取り除いた要素を返すにはつぎのように書く。
@example
(prog1 (car x) (setq x (cdr x)))
@end example
@end defspec
@defspec prog2 form1 form2 forms@dots{}
このスペシャルフォームは、@var{form1}、@var{form2}、@var{forms}の
フォームすべてをテキスト上の順に評価し、@var{form2}の結果を返す。
@example
@group
(prog2 (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The second form"
@end group
@end example
@end defspec
@node Conditionals
@section 条件付き実行
@cindex 条件付き評価
条件付き制御構造は、選択肢を選びます。
Emacs Lispには、4つの条件付きフォームがあります。
他の言語のものとほとんど同じ@code{if}、
@code{if}の変形である@code{when}や@code{unless}、
一般化したcase文である@code{cond}です。
@defspec if condition then-form else-forms@dots{}
@code{if}は、@var{condition}をもとにして、
@var{then-form}か@var{else-forms}を選ぶ。
@var{condition}が@code{nil}以外に評価されると、
@var{then-form}を評価し、その結果を返す。
さもなければ、@var{else-forms}をテキスト上の順に評価し、
その最後のものの値を返す。
(@code{if}の@var{else}部分は、暗黙の@code{progn}の例である。
@xref{Sequencing}。)
@var{condition}が値@code{nil}であり、かつ、@var{else-forms}がないと、
@code{if}は@code{nil}を返す。
@code{if}がスペシャルフォームであるのは、
選択しなかった分岐をけっして評価しないからである。
したがって、つぎの例では、
@code{print}はけっして呼ばれないため@code{true}は表示されない。
@example
@group
(if nil
(print 'true)
'very-false)
@result{} very-false
@end group
@end example
@end defspec
@defmac when condition then-forms@dots{}
@tindex when
これは@code{if}の変形であり、@var{else-forms}がなく、
@var{then-forms}は複数のフォームでもよい。
特に、
@example
(when @var{condition} @var{a} @var{b} @var{c})
@end example
@noindent
は、つぎとまったく等価である。
@example
(if @var{condition} (progn @var{a} @var{b} @var{c}) nil)
@end example
@end defmac
@defmac unless condition forms@dots{}
@tindex condition
これは@var{then-form}がない@code{if}の変形である。
@example
(unless @var{condition} @var{a} @var{b} @var{c})
@end example
@noindent
は、つぎとまったく等価である。
@example
(if @var{condition} nil
@var{a} @var{b} @var{c})
@end example
@end defmac
@defspec cond clause@dots{}
@code{cond}は任意個数の選択肢から1つを選ぶ。
@code{cond}の各節@var{clause}はリストである必要がある。
このリストの@sc{car}が@var{condition}(条件)である。
残りの要素は、あれば、@var{body-forms}(本体フォーム)である。
つまり、各節はつぎのようになる。
@example
(@var{condition} @var{body-forms}@dots{})
@end example
@code{cond}は、各節の@var{condition}を評価して、
各節をテキスト上の順に試す。
@var{condition}の値が@code{nil}以外であれば、
その節は『成功』する。
そうすると、@code{cond}はその節の@var{body-forms}を評価し、
@var{body-forms}の最後の値が返される。
残りの節は無視する。
@var{condition}の値が@code{nil}であると、
その節は『失敗』し、
@code{cond}はつぎの節へ移りその@var{condition}を試す。
節@var{clause}は、つぎの形式でもよい。
@example
(@var{condition})
@end example
@noindent
この場合、@var{condition}が@code{nil}以外であると、
@var{condition}が@code{cond}フォームの値になる。
If every @var{condition} evaluates to @code{nil}, so that every clause
fails, @code{cond} returns @code{nil}.
以下の例には4つの節があり、
@code{x}の値が、数、文字列、バッファ、シンボルかどうか調べる。
@example
@group
(cond ((numberp x) x)
((stringp x) x)
((bufferp x)
(setq temporary-hack x) ; @r{1つの節に}
(buffer-name x)) ; @r{複数個の本体フォーム}
((symbolp x) (symbol-value x)))
@end group
@end example
最後の節を除くそれよりまえの節がどれも成功しないときには、
最後の節を実行したいことがしばしばある。
これを行うには、@code{(t @var{body-forms})}のように
最後の節の@var{condition}に@code{t}を使う。
フォーム@code{t}は@code{t}と評価され、けっして@code{nil}ではない。
そのため、@code{cond}がこの節に達したときには、
この節が失敗することはない。たとえば、つぎのとおり。
@example
@group
(setq a 5)
(cond ((eq a 'hack) 'foo)
(t "default"))
@result{} "default"
@end group
@end example
@noindent
この式は、@code{a}の値が@code{hack}のときには@code{foo}を返し、
さもなければ文字列@code{"default"}を返す@code{cond}である。
@end defspec
任意の条件付き構造は、@code{cond}や@code{if}で表現できます。
したがって、どちらを使うかは好みの問題です。
たとえば、つぎのとおりです。
@example
@group
(if @var{a} @var{b} @var{c})
@equiv{}
(cond (@var{a} @var{b}) (t @var{c}))
@end group
@end example
@menu
* Pattern matching case statement::
@end menu
@node Pattern matching case statement
@subsection Pattern matching case statement
@cindex pcase
@cindex pattern matching
To compare a particular value against various possible cases, the macro
@code{pcase} can come handy. It takes the following form:
@example
(pcase @var{exp} @var{branch}1 @var{branch}2 @var{branch}3 @dots{})
@end example
where each @var{branch} takes the form @code{(@var{upattern}
@var{body-forms}@dots{})}.
It will first evaluate @var{exp} and then compare the value against each
@var{upattern} to see which @var{branch} to use, after which it will run the
corresponding @var{body-forms}. A common use case is to distinguish
between a few different constant values:
@example
(pcase (get-return-code x)
(`success (message "Done!"))
(`would-block (message "Sorry, can't do it now"))
(`read-only (message "The shmliblick is read-only"))
(`access-denied (message "You do not have the needed rights"))
(code (message "Unknown return code %S" code)))
@end example
In the last clause, @code{code} is a variable that gets bound to the value that
was returned by @code{(get-return-code x)}.
To give a more complex example, a simple interpreter for a little
expression language could look like (note that this example requires
lexical binding):
@example
(defun evaluate (exp env)
(pcase exp
(`(add ,x ,y) (+ (evaluate x env) (evaluate y env)))
(`(call ,fun ,arg) (funcall (evaluate fun env) (evaluate arg env)))
(`(fn ,arg ,body) (lambda (val)
(evaluate body (cons (cons arg val) env))))
((pred numberp) exp)
((pred symbolp) (cdr (assq exp env)))
(_ (error "Unknown expression %S" exp))))
@end example
Where @code{`(add ,x ,y)} is a pattern that checks that @code{exp} is a three
element list starting with the symbol @code{add}, then extracts the second and
third elements and binds them to the variables @code{x} and @code{y}.
@code{(pred numberp)} is a pattern that simply checks that @code{exp}
is a number, and @code{_} is the catch-all pattern that matches anything.
Here are some sample programs including their evaluation results:
@example
(evaluate '(add 1 2) nil) ;=> 3
(evaluate '(add x y) '((x . 1) (y . 2))) ;=> 3
(evaluate '(call (fn x (add 1 x)) 2) nil) ;=> 3
(evaluate '(sub 1 2) nil) ;=> error
@end example
There are two kinds of patterns involved in @code{pcase}, called
@emph{U-patterns} and @emph{Q-patterns}. The @var{upattern} mentioned above
are U-patterns and can take the following forms:
@table @code
@item `@var{qpattern}
This is one of the most common form of patterns. The intention is to mimic the
backquote macro: this pattern matches those values that could have been built
by such a backquote expression. Since we're pattern matching rather than
building a value, the unquote does not indicate where to plug an expression,
but instead it lets one specify a U-pattern that should match the value at
that location.
More specifically, a Q-pattern can take the following forms:
@table @code
@item (@var{qpattern1} . @var{qpattern2})
This pattern matches any cons cell whose @code{car} matches @var{qpattern1} and
whose @code{cdr} matches @var{pattern2}.
@item [@var{qpattern1} @var{qpattern2} @dots{} @var{qpatternm}]
This pattern matches a vector of length @var{M} whose 0..(@var{M}-1)th
elements match @var{qpattern1}, @var{qpattern2} @dots{} @var{qpatternm},
respectively.
@item @var{atom}
This pattern matches any atom @code{equal} to @var{atom}.
@item ,@var{upattern}
This pattern matches any object that matches the @var{upattern}.
@end table
@item @var{symbol}
A mere symbol in a U-pattern matches anything, and additionally let-binds this
symbol to the value that it matched, so that you can later refer to it, either
in the @var{body-forms} or also later in the pattern.
@item _
This so-called @emph{don't care} pattern matches anything, like the previous
one, but unlike symbol patterns it does not bind any variable.
@item (pred @var{pred})
This pattern matches if the function @var{pred} returns non-@code{nil} when
called with the object being matched.
@item (or @var{upattern1} @var{upattern2}@dots{})
This pattern matches as soon as one of the argument patterns succeeds.
All argument patterns should let-bind the same variables.
@item (and @var{upattern1} @var{upattern2}@dots{})
This pattern matches only if all the argument patterns succeed.
@item (guard @var{exp})
This pattern ignores the object being examined and simply succeeds if @var{exp}
evaluates to non-@code{nil} and fails otherwise. It is typically used inside
an @code{and} pattern. For example, @code{(and x (guard (< x 10)))}
is a pattern which matches any number smaller than 10 and let-binds it to
the variable @code{x}.
@end table
@node Combining Conditions
@section 条件の組み合わせ
本節では、@code{if}や@code{cond}とともに用いて複雑な条件を表現するために
しばしば使われる3つの構造を説明します。
@code{and}や@code{or}の構造は、
複数の条件付き構造の一種として単独で使うこともできます。
@defun not condition
この関数は、@var{condition}が偽であるかどうか調べる。
@var{condition}が@code{nil}であれば@code{t}を返し、
さもなければ@code{nil}を返す。
関数@code{not}は@code{null}と同一であるが、
空リストかどうか調べる場合には、@code{null}を使うことを勧める。
@end defun
@defspec and conditions@dots{}
スペシャルフォーム@code{and}は、
すべての@var{conditions}が真であるかどうか調べる。
@var{conditions}を1つ1つ書かれた順に評価して調べる。
@var{conditions}のどれかが@code{nil}に評価されると、
@code{and}の結果は、残りの@var{conditions}に関係なく、@code{nil}になる。
つまり、@code{and}はただちに@code{nil}を返し、
@var{conditions}の残りを無視する。
@var{conditions}すべてが@code{nil}以外であることがわかると、
それらの最後の値がフォーム@code{and}の値となる。
Just
@code{(and)}, with no @var{conditions}, returns @code{t}, appropriate
because all the @var{conditions} turned out non-@code{nil}. (Think
about it; which one did not?)
例を示そう。
最初の条件は整数1を返し、これは@code{nil}ではない。
同様に、2番目の条件は整数2を返し、@code{nil}ではない。
3番目の条件は@code{nil}なので、残りの条件を評価しない。
@example
@group
(and (print 1) (print 2) nil (print 3))
@print{} 1
@print{} 2
@result{} nil
@end group
@end example
@code{and}を使ったより現実的な例はつぎのとおり。
@example
@group
(if (and (consp foo) (eq (car foo) 'x))
(message "foo is a list starting with x"))
@end group
@end example
@noindent
@code{(consp foo)}が@code{nil}を返すと@code{(car foo)}は実行されず、
そのためエラーを回避することに注意。
@code{and}は、@code{if}や@code{cond}で表現できる。
たとえば、つぎのとおり。
@example
@group
(and @var{arg1} @var{arg2} @var{arg3})
@equiv{}
(if @var{arg1} (if @var{arg2} @var{arg3}))
@equiv{}
(cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
@end group
@end example
@end defspec
@defspec or conditions@dots{}
スペシャルフォーム@code{or}は、
@var{conditions}の少なくとも1つが真であるかどうか調べる。
@var{conditions}を1つ1つ書かれた順に評価して調べる。
@var{conditions}のどれかが@code{nil}以外に評価されると、
@code{or}の結果は@code{nil}以外になる。
そして、@code{or}はただちに完了し、
@var{conditions}の残りを無視する。
戻り値は、@code{nil}以外に評価された値である。
@var{conditions}すべてが@code{nil}であることがわかると、
@code{or}は@code{nil}を返す。
Just @code{(or)}, with no
@var{conditions}, returns @code{nil}, appropriate because all the
@var{conditions} turned out @code{nil}. (Think about it; which one
did not?)
たとえば、つぎの式は、@code{x}が0か@code{nil}であることを調べる。
@example
(or (eq x nil) (eq x 0))
@end example
@code{and}構造と同様に、@code{or}は@code{cond}で書き表せる。
たとえば、つぎのとおり。
@example
@group
(or @var{arg1} @var{arg2} @var{arg3})
@equiv{}
(cond (@var{arg1})
(@var{arg2})
(@var{arg3}))
@end group
@end example
@code{or}を@code{if}で書くこともだいたいできるが、
途中で抜け出せない。
@example
@group
(if @var{arg1} @var{arg1}
(if @var{arg2} @var{arg2}
@var{arg3}))
@end group
@end example
@noindent
これは完全には同一ではない。
というのは、@var{arg1}や@var{arg2}を2度評価するからである。
一方、@code{(or @var{arg1} @var{arg2} @var{arg3})}は、
どの引数も一度だけ評価する。
@end defspec
@node Iteration
@section 繰り返し
@cindex 繰り返し
@cindex 再帰
繰り返しとは、プログラムのある部分を何度も実行することです。
たとえば、リストの各要素や0から@var{n}の各整数について
1回ずつある計算を行いたい場合です。
Emacs Lispでこれを行うには、スペシャルフォーム@code{while}を使います。
@defspec while condition forms@dots{}
@code{while}は、まず@var{condition}を評価する。
結果が@code{nil}以外であれば、@var{forms}をテキスト上の順で評価する。
そして、@var{condition}を評価し直し、その結果が@code{nil}以外であれば、
再度@var{forms}を評価する。
この処理を@var{condition}が@code{nil}に評価されるまで繰り返す。
繰り返し回数に制限はない。
ループは、@var{condition}が@code{nil}に評価される、
エラーが発生する、@code{throw}によりループから抜け出す
(@pxref{Nonlocal Exits})のいずれかが起こるまで繰り返される。
フォーム@code{while}の値はつねに@code{nil}である。
@example
@group
(setq num 0)
@result{} 0
@end group
@group
(while (< num 4)
(princ (format "Iteration %d." num))
(setq num (1+ num)))
@print{} Iteration 0.
@print{} Iteration 1.
@print{} Iteration 2.
@print{} Iteration 3.
@result{} nil
@end group
@end example
終了検査のまえに各繰り返しごとに実行したいことがあれば、
以下のように、それらと終了検査を@code{progn}でまとめたものを
@code{while}の第1引数にする。
@example
@group
(while (progn
(forward-line 1)
(not (looking-at "^$"))))
@end group
@end example
@noindent
これは、1行先へ移動し、空行に達するまで、移動を繰り返す。
この@code{while}には本体がなく、
終了検査(かつポイントを実際に動かす)だけであるという点で、
風変わりである。
@end defspec
The @code{dolist} and @code{dotimes} macros provide convenient ways to
write two common kinds of loops.
@defmac dolist (var list [result]) body@dots{}
This construct executes @var{body} once for each element of
@var{list}, binding the variable @var{var} locally to hold the current
element. Then it returns the value of evaluating @var{result}, or
@code{nil} if @var{result} is omitted. For example, here is how you
could use @code{dolist} to define the @code{reverse} function:
@example
(defun reverse (list)
(let (value)
(dolist (elt list value)
(setq value (cons elt value)))))
@end example
@end defmac
@defmac dotimes (var count [result]) body@dots{}
This construct executes @var{body} once for each integer from 0
(inclusive) to @var{count} (exclusive), binding the variable @var{var}
to the integer for the current iteration. Then it returns the value
of evaluating @var{result}, or @code{nil} if @var{result} is omitted.
Here is an example of using @code{dotimes} to do something 100 times:
@example
(dotimes (i 100)
(insert "I will not obey absurd orders\n"))
@end example
@end defmac
@node Generators
@section Generators
@cindex generators
A @dfn{generator} is a function that produces a potentially-infinite
stream of values. Each time the function produces a value, it
suspends itself and waits for a caller to request the next value.
@defmac iter-defun name args [doc] [declare] [interactive] body@dots{}
@code{iter-defun} defines a generator function. A generator function
has the same signature as a normal function, but works differently.
Instead of executing @var{body} when called, a generator function
returns an iterator object. That iterator runs @var{body} to generate
values, emitting a value and pausing where @code{iter-yield} or
@code{iter-yield-from} appears. When @var{body} returns normally,
@code{iter-next} signals @code{iter-end-of-sequence} with @var{body}'s
result as its condition data.
Any kind of Lisp code is valid inside @var{body}, but
@code{iter-yield} and @code{iter-yield-from} cannot appear inside
@code{unwind-protect} forms.
@end defmac
@defmac iter-lambda args [doc] [interactive] body@dots{}
@code{iter-lambda} produces an unnamed generator function that works
just like a generator function produced with @code{iter-defun}.
@end defmac
@defmac iter-yield value
When it appears inside a generator function, @code{iter-yield}
indicates that the current iterator should pause and return
@var{value} from @code{iter-next}. @code{iter-yield} evaluates to the
@code{value} parameter of next call to @code{iter-next}.
@end defmac
@defmac iter-yield-from iterator
@code{iter-yield-from} yields all the values that @var{iterator}
produces and evaluates to the value that @var{iterator}'s generator
function returns normally. While it has control, @var{iterator}
receives values sent to the iterator using @code{iter-next}.
@end defmac
To use a generator function, first call it normally, producing a
@dfn{iterator} object. An iterator is a specific instance of a
generator. Then use @code{iter-next} to retrieve values from this
iterator. When there are no more values to pull from an iterator,
@code{iter-next} raises an @code{iter-end-of-sequence} condition with
the iterator's final value.
It's important to note that generator function bodies only execute
inside calls to @code{iter-next}. A call to a function defined with
@code{iter-defun} produces an iterator; you must ``drive'' this
iterator with @code{iter-next} for anything interesting to happen.
Each call to a generator function produces a @emph{different}
iterator, each with its own state.
@defun iter-next iterator value
Retrieve the next value from @var{iterator}. If there are no more
values to be generated (because @var{iterator}'s generator function
returned), @code{iter-next} signals the @code{iter-end-of-sequence}
condition; the data value associated with this condition is the value
with which @var{iterator}'s generator function returned.
@var{value} is sent into the iterator and becomes the value to which
@code{iter-yield} evaluates. @var{value} is ignored for the first
@code{iter-next} call to a given iterator, since at the start of
@var{iterator}'s generator function, the generator function is not
evaluating any @code{iter-yield} form.
@end defun
@defun iter-close iterator
If @var{iterator} is suspended inside an @code{unwind-protect}'s
@code{bodyform} and becomes unreachable, Emacs will eventually run
unwind handlers after a garbage collection pass. (Note that
@code{iter-yield} is illegal inside an @code{unwind-protect}'s
@code{unwindforms}.) To ensure that these handlers are run before
then, use @code{iter-close}.
@end defun
Some convenience functions are provided to make working with
iterators easier:
@defmac iter-do (var iterator) body @dots{}
Run @var{body} with @var{var} bound to each value that
@var{iterator} produces.
@end defmac
The Common Lisp loop facility also contains features for working with
iterators. See @xref{Loop Facility,,,cl,Common Lisp Extensions}.
The following piece of code demonstrates some important principles of
working with iterators.
@example
(iter-defun my-iter (x)
(iter-yield (1+ (iter-yield (1+ x))))
;; Return normally
-1)
(let* ((iter (my-iter 5))
(iter2 (my-iter 0)))
;; Prints 6
(print (iter-next iter))
;; Prints 9
(print (iter-next iter 8))
;; Prints 1; iter and iter2 have distinct states
(print (iter-next iter2 nil))
;; We expect the iter sequence to end now
(condition-case x
(iter-next iter)
(iter-end-of-sequence
;; Prints -1, which my-iter returned normally
(print (cdr x)))))
@end example
@node Nonlocal Exits
@section 非ローカル脱出
@cindex 非ローカル脱出
@dfn{非ローカル脱出}(nonlocal exit)とは、
プログラムのある場所から別の離れた場所へ制御を移すことです。
Emacs Lispでは、エラーの結果として非ローカル脱出が発生します。
非ローカル脱出は、明示的な制御にも使えます。
非ローカル脱出は、脱出対象の構造で作成したすべての変数束縛を解きます。
@menu
* Catch and Throw:: Nonlocal exits for the program's own purposes.
* Examples of Catch:: Showing how such nonlocal exits can be written.
* Errors:: How errors are signaled and handled.
* Cleanups:: Arranging to run a cleanup form if an error happens.
@end menu
@node Catch and Throw
@subsection 明示的な非ローカル脱出:@code{ }@code{catch}と@code{throw}
ほとんどの制御構造は、その構造内での制御の流れだけに影響します。
関数@code{throw}は、通常のプログラム実行のこのような規則の例外です。
つまり、要求に従って非ローカルな脱出を行います。
(ほかにも例外はあるが、それらはエラー処理のためだけである。)
@code{throw}は@code{catch}の内側で使い、
その@code{catch}へ戻ります。
@example
@group
(defun foo-outer ()
(catch 'foo
(foo-inner)))
(defun foo-inner ()
@dots{}
(if x
(throw 'foo t))
@dots{})
@end group
@end example
@noindent
フォーム@code{throw}を実行すると、対応する@code{catch}へ制御が戻り、
ただちに終了します。
@code{throw}に続くコードは実行されません。
@code{throw}の第2引数は、@code{catch}の戻り値として使われます。
関数@code{throw}は、その第1引数に基づいて対応する@code{catch}を探します。
つまり、@code{catch}の第1引数が
@code{throw}に指定されたものに@code{eq}であるものを探します。
そのような@code{catch}が複数個ある場合には、
もっとも内側のものを優先します。
したがって、上の例では、@code{throw}は@code{foo}を指定し、
@code{foo-outer}の@code{catch}は同じシンボルを指定しているので、
その@code{catch}を使います
(ただし、これらのあいだには他の一致する@code{catch}がないとして)。
@code{throw}の実行により、
対応する@code{catch}までのすべてのLispの構造を抜け出します。
これには関数呼び出しも含みます。
@code{let}や関数呼び出しなどの束縛を作る構造からもこのように抜け出すので、
通常どおり抜け出す場合と同様に束縛を解きます
(@pxref{Local Variables})。
同様に、@code{throw}は、@code{save-excursion}(@pxref{Excursions})で
保存したバッファや位置情報、
@code{save-restriction}で保存したナロイング状態も復元します。
さらに、スペシャルフォーム@code{unwind-protect}で設定した後始末を
このフォームから抜け出すときに実行します(@pxref{Cleanups})。
@code{throw}は、テキスト上で、
ジャンプ先である@code{catch}の内側に現れる必要はありません。
@code{catch}内から呼ばれた別の関数からも戻ることもできます。
@code{throw}の実行が、
時間的に@code{catch}に入ったあとで、かつ、それから抜けるまえである限り、
対応する@code{catch}を参照できます。
エディタコマンドループ(@pxref{Recursive Editing})から抜ける
@code{exit-recursive-edit}などのコマンドで
@code{throw}を使えるのは、このような理由からです。
@cindex CLに関した注意--Emacsでは@code{throw}のみ
@quotation
@b{Common Lispに関した注意:}
Common Lispを含むほとんどの他のLispには、
非逐次的に制御を移す方法がいくつかある。
たとえば、@code{return}、@code{return-from}、@code{go}。
Emacs Lispには@code{throw}しかない。
@file{cl-lib}ライブラリは、上記の幾つかを提供する。
@xref{Blocks and Exits,,,cl,Common Lisp Extensions}。
@end quotation
@defspec catch tag body@dots{}
@cindex 実行時スタック上のタグ
@code{catch}は、関数@code{throw}向けに戻り位置を確立する。
その戻り位置は、@var{tag}によって他の戻り位置と区別され、
@code{nil}以外ならば任意のLispオブジェクトでよい。
引数@var{tag}は、戻り位置を確立するまえに、通常どおり評価される。
戻り位置を確立してから、@code{catch}は、@var{body}のフォームを
テキスト上の順に評価する。
エラーや非ローカル脱出なしにフォームの実行が普通に終了した場合、
@code{catch}は、最後の本体フォームの値を返す。
@var{body}の内側で、@var{tag}と同じ値を指定した@code{throw}が実行されると、
@code{catch}はただちに終了する。
このとき返す値は、@code{throw}の第2引数に指定されたものである。
@end defspec
@defun throw tag value
@code{throw}の目的は、
@code{catch}でまえもって確立しておいた戻り位置へ復帰することである。
引数@var{tag}は、さまざまな既存の戻り位置から選ぶために使い、
@code{catch}で指定した値と@code{eq}である必要がある。
@var{tag}に複数の戻り位置が一致する場合には、もっとも内側のものを使う。
引数@var{value}は、対応する@code{catch}の戻り値として使う。
@kindex no-catch
タグ@var{tag}である有効な戻り位置がなければ、
@code{(@var{tag} @var{value})}を伴ったエラー@code{no-catch}を通知する。
@end defun
@node Examples of Catch
@subsection @code{catch}と@code{throw}の例
@code{catch}と@code{throw}の使い方の1つは、
2重のループからの脱出です。
(ほとんどの言語では、これを『go to』で行うであろう。)
ここでは、@var{i}と@var{j}を0から9に変えながら、
@code{(foo @var{i} @var{j})}を計算します。
@example
@group
(defun search-foo ()
(catch 'loop
(let ((i 0))
(while (< i 10)
(let ((j 0))
(while (< j 10)
(if (foo i j)
(throw 'loop (list i j)))
(setq j (1+ j))))
(setq i (1+ i))))))
@end group
@end example
@noindent
@code{foo}がある時点で@code{nil}以外を返すと、
ただちに止まって@var{i}と@var{j}のリストを返します。
@code{foo}がつねに@code{nil}を返すと、
@code{catch}は通常どおりに戻り、
@code{while}の結果である@code{nil}を返します。
2つの巧妙な例をあげましょう。
多少異なる2つの戻り位置が同時に存在します。
まず、同じタグ@code{hack}で2つの戻り位置があります。
@example
@group
(defun catch2 (tag)
(catch tag
(throw 'hack 'yes)))
@result{} catch2
@end group
@group
(catch 'hack
(print (catch2 'hack))
'no)
@print{} yes
@result{} no
@end group
@end example
@noindent
どちらの戻り位置も@code{throw}に一致するタグなので、
内側のもの、つまり、@code{catch2}で確立したものに戻ります。
したがって、@code{catch2}は値@code{yes}で通常どおり戻り、
この値が表示されます。
最後に、外側の@code{catch}の2番目の本体フォーム、
つまり、@code{'no}が評価され、外側の@code{catch}から戻ります。
今度は、@code{catch2}に指定する引数を変更してみます。
@example
@group
(catch 'hack
(print (catch2 'quux))
'no)
@result{} yes
@end group
@end example
@noindent
ここでも2つの戻り位置がありますが、
今度は外側のものだけがタグ@code{hack}です。
内側のものはタグ@code{quux}です。
したがって、@code{throw}により、外側の@code{catch}が値@code{yes}を返します。
関数@code{print}はけっして呼ばれず、
本体フォーム@code{'no}もけっして評価されません。
@node Errors
@subsection エラー
@cindex エラー
Emacs Lispが、なんらかの理由で評価できないフォームを評価しようとしたときには、
Emacs Lispは@dfn{エラー}(error)を@dfn{通知}(signals)します。
エラーが通知されると、Emacsのデフォルトの動作は、
エラーメッセージを表示し、現在のコマンドの実行を終了します。
バッファの末尾で@kbd{C-f}を打ったときなどのように、
これはほとんどの場合、適切なことです。
複雑なプログラムでは、単に終了するだけでは満足できないこともあります。
たとえば、プログラムではデータ構造に一時的な変更を加えていたり、
プログラム終了時には削除する必要がある一時的なバッファを作成するでしょう。
そのような場合には、@code{unwind-protect}を使って、
エラー発生時に評価される@dfn{後始末式}(cleanup expressions)を
確立しておきます。
(@xref{Cleanups}。)
場合によっては、サブルーティンでエラーが発生しても、
プログラムの実行を継続したいこともあるでしょう。
このような場合には、@code{condition-case}を使って、
エラー状態から制御を回復するための
@dfn{エラーハンドラ}(error handlers)を確立しておきます。
エラー処理を用いてプログラムのある場所から別の場所へ制御を移す、
という誘惑には耐えてください。
そのかわりに@code{catch}と@code{throw}を使いましょう。
@xref{Catch and Throw}。
@menu
* Signaling Errors:: How to report an error.
* Processing of Errors:: What Emacs does when you report an error.
* Handling Errors:: How you can trap errors and continue execution.
* Error Symbols:: How errors are classified for trapping them.
@end menu
@node Signaling Errors
@subsubsection エラーの通知方法
@cindex エラー通知
@dfn{Signaling} an error means beginning error processing. Error