-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
3093 lines (1405 loc) · 229 KB
/
index.html
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
<!DOCTYPE html>
<html class="theme-next gemini use-motion" lang="zh-tw">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=6.2.0" rel="stylesheet" type="text/css" />
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.2.0">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.2.0">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.2.0">
<link rel="mask-icon" href="/images/logo.svg?v=6.2.0" color="#222">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Gemini',
version: '6.2.0',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: false,
fastclick: false,
lazyload: false,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<meta name="description" content="This is a programming blog">
<meta property="og:type" content="website">
<meta property="og:title" content="Programming blog">
<meta property="og:url" content="https://pandaforme.github.io/index.html">
<meta property="og:site_name" content="Programming blog">
<meta property="og:description" content="This is a programming blog">
<meta property="og:locale" content="zh-tw">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Programming blog">
<meta name="twitter:description" content="This is a programming blog">
<link rel="alternate" href="/atom.xml" title="Programming blog" type="application/atom+xml" />
<link rel="canonical" href="https://pandaforme.github.io/"/>
<script type="text/javascript" id="page.configurations">
CONFIG.page = {
sidebar: "",
};
</script>
<title>Programming blog</title>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-53742025-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-53742025-1');
</script>
<noscript>
<style type="text/css">
.use-motion .motion-element,
.use-motion .brand,
.use-motion .menu-item,
.sidebar-inner,
.use-motion .post-block,
.use-motion .pagination,
.use-motion .comments,
.use-motion .post-header,
.use-motion .post-body,
.use-motion .collection-title { opacity: initial; }
.use-motion .logo,
.use-motion .site-title,
.use-motion .site-subtitle {
opacity: initial;
top: initial;
}
.use-motion {
.logo-line-before i { left: initial; }
.logo-line-after i { right: initial; }
}
</style>
</noscript>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-tw">
<div class="container sidebar-position-left
page-home">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">Programming blog</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle">This is a programming blog</p>
</div>
<div class="site-nav-toggle">
<button aria-label="Toggle navigation bar">
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home menu-item-active">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />Home</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />Tags</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />Categories</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archives</a>
</li>
<li class="menu-item menu-item-sitemap">
<a href="/sitemap.xml" rel="section">
<i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />Sitemap</a>
</li>
<li class="menu-item menu-item-search">
<a href="javascript:;" class="popup-trigger">
<i class="menu-item-icon fa fa-search fa-fw"></i> <br />Search</a>
</li>
</ul>
<div class="site-search">
<div class="popup search-popup local-search-popup">
<div class="local-search-header clearfix">
<span class="search-icon">
<i class="fa fa-search"></i>
</span>
<span class="popup-btn-close">
<i class="fa fa-times-circle"></i>
</span>
<div class="local-search-input-wrapper">
<input autocomplete="off"
placeholder="Searching..." spellcheck="false"
type="text" id="local-search-input">
</div>
</div>
<div id="local-search-result"></div>
</div>
</div>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<section id="posts" class="posts-expand">
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="https://pandaforme.github.io/2018/05/25/Java-Flow-control-in-try-catch-finally/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="pandaforme">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Programming blog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2018/05/25/Java-Flow-control-in-try-catch-finally/" itemprop="url">
[Java] Flow control in try catch finally
</a>
</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">Posted on</span>
<time title="Created: 2018-05-25 11:35:00 / Modified: 11:55:13" itemprop="dateCreated datePublished" datetime="2018-05-25T11:35:00+08:00">2018-05-25</time>
</span>
<span class="post-comments-count">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-comment-o"></i>
</span>
<a href="/2018/05/25/Java-Flow-control-in-try-catch-finally/#comments" itemprop="discussionUrl">
<span class="post-comments-count disqus-comment-count"
data-disqus-identifier="2018/05/25/Java-Flow-control-in-try-catch-finally/" itemprop="commentCount"></span>
</a>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>在正常情況下,當執行完 try 的最後一行或是要把控制權轉交給它的呼叫者 (return 或丟出 exception)時,會執行 finally ,當 finally 執行完畢,再把控制權轉交給 try。</p>
<p>但是當在 finally 裡面寫下 return, throw exception, continue, break 會沒有辦法把控制權轉交給 try,造成不可以預期的結果。所以<strong>千萬</strong>不要在 finally 裡面 return 或丟出 exception,雖然現在的 IDE 都會聰明到幫你檢查出來。</p>
<p>主要原因 try-finally 轉成 Java byte code 時候,finally 是一個副程式,當 try 執行完畢時候就會去呼叫 finally 副程式。當 finally 副程式執行完畢,會跳到 try 的記憶體位置。但在 finally 裡面加了這些return, throw exception, continue, break,它就提前跳出程式回不到正確的位置。</p>
<p>另外,當 try 裡面強制中斷 JVM 或是非預期的情況發生提早結束 (這裡所指的非預期的情況不是丟出 exception,而是當下的 thread 突然死掉或是 JVM 突然有問題這類的。),finally 是不會執行的。</p>
<h1 id="Try-finally-clause"><a href="#Try-finally-clause" class="headerlink" title="Try-finally clause"></a>Try-finally clause</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> {</span><br><span class="line"> <span class="comment">// Block of code with multiple exit points</span></span><br><span class="line">}</span><br><span class="line"><span class="keyword">finally</span> {</span><br><span class="line"> <span class="comment">// Block of code that is always executed when the try block is exited,</span></span><br><span class="line"> <span class="comment">// no matter how the try block is exited</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="Example-1"><a href="#Example-1" class="headerlink" title="Example 1"></a>Example 1</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> i = <span class="number">0</span>; </span><br><span class="line"><span class="keyword">try</span> { </span><br><span class="line"> i = i + <span class="number">1</span>; </span><br><span class="line"> System.out.println(i);</span><br><span class="line">}</span><br><span class="line"><span class="keyword">finally</span>{</span><br><span class="line"> i = i + <span class="number">2</span>; </span><br><span class="line"> System.out.println(i);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">//1</span></span><br><span class="line"><span class="comment">//3</span></span><br></pre></td></tr></table></figure>
<h1 id="Example-2"><a href="#Example-2" class="headerlink" title="Example 2"></a>Example 2</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>{</span><br><span class="line"> System.out.println(doSomeThing());</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">doSomeThing</span><span class="params">()</span></span>{</span><br><span class="line"> <span class="keyword">try</span> { </span><br><span class="line"> <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">finally</span>{</span><br><span class="line"> <span class="keyword">return</span> <span class="number">2</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<h1 id="Example-3"><a href="#Example-3" class="headerlink" title="Example 3"></a>Example 3</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line"> System.out.println(doSomeThing(<span class="keyword">true</span>));</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">doSomeThing</span><span class="params">(<span class="keyword">boolean</span> bVal)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">if</span> (bVal) {</span><br><span class="line"> <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line"> } <span class="keyword">finally</span> {</span><br><span class="line"> System.out.println(<span class="string">"Got old fashioned."</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// Got old fashioned.</span></span><br><span class="line"><span class="comment">// 1</span></span><br></pre></td></tr></table></figure>
<h1 id="Example-4"><a href="#Example-4" class="headerlink" title="Example 4"></a>Example 4</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line"> System.out.println(doSomeThing());</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">doSomeThing</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"from try"</span>);</span><br><span class="line"> } <span class="keyword">finally</span> {</span><br><span class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"from finally"</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// Exception in thread "main" java.lang.Exception: from finally</span></span><br></pre></td></tr></table></figure>
<h1 id="Example-5"><a href="#Example-5" class="headerlink" title="Example 5"></a>Example 5</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line"> System.out.println(doSomeThing(<span class="keyword">true</span>));</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">doSomeThing</span><span class="params">(<span class="keyword">boolean</span> bVal)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line"> <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line"> <span class="keyword">while</span> (<span class="keyword">true</span>) {</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> i = <span class="number">1</span>;</span><br><span class="line"> } <span class="keyword">finally</span> { <span class="comment">// the first finally clause</span></span><br><span class="line"> i = <span class="number">2</span>;</span><br><span class="line"> }</span><br><span class="line"> i = <span class="number">3</span>;</span><br><span class="line"> <span class="keyword">return</span> i; <span class="comment">// this never completes, because of the continue</span></span><br><span class="line"> } <span class="keyword">finally</span> { <span class="comment">// the second finally clause</span></span><br><span class="line"> <span class="keyword">if</span> (i == <span class="number">3</span>) {</span><br><span class="line"> <span class="keyword">continue</span>; <span class="comment">// this continue overrides the return statement</span></span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h1 id="Example-6"><a href="#Example-6" class="headerlink" title="Example 6"></a>Example 6</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line"> System.out.println(doSomeThing());</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">doSomeThing</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>{</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> System.exit(<span class="number">1</span>);</span><br><span class="line"> } <span class="keyword">finally</span> {</span><br><span class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"from finally"</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// terminates JVM and doesn't execute finally block</span></span><br></pre></td></tr></table></figure>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><p><a href="https://www.javaworld.com/article/2077609/core-java/try-finally-clauses-defined-and-demonstrated.html" target="_blank" rel="noopener">Try-finally clauses defined and demonstrated</a></p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="https://pandaforme.github.io/2017/04/26/Scala-The-importance-of-recursion/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="pandaforme">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Programming blog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2017/04/26/Scala-The-importance-of-recursion/" itemprop="url">
[Scala] The importance of recursion
</a>
</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">Posted on</span>
<time title="Created: 2017-04-26 17:55:00" itemprop="dateCreated datePublished" datetime="2017-04-26T17:55:00+08:00">2017-04-26</time>
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-calendar-check-o"></i>
</span>
<span class="post-meta-item-text">Edited on</span>
<time title="Modified: 2017-05-14 00:20:49" itemprop="dateModified" datetime="2017-05-14T00:20:49+08:00">2017-05-14</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">In</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Scala/" itemprop="url" rel="index"><span itemprop="name">Scala</span></a></span>
</span>
<span class="post-comments-count">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-comment-o"></i>
</span>
<a href="/2017/04/26/Scala-The-importance-of-recursion/#comments" itemprop="discussionUrl">
<span class="post-comments-count disqus-comment-count"
data-disqus-identifier="2017/04/26/Scala-The-importance-of-recursion/" itemprop="commentCount"></span>
</a>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<h1 id="遞迴"><a href="#遞迴" class="headerlink" title="遞迴"></a>遞迴</h1><p>在functional programming世界中是不准許有mutable變數,意味著我們熟悉的 <code>while</code>, <code>for</code> 迴圈都是禁止使用。<br>那我們應該怎麼辦呢? 這邊會舉個數個例子,來解釋是透過遞迴方式來完成 <code>while</code> 或 <code>for</code> 迴圈。</p>
<h2 id="從一個串列中找出最大值"><a href="#從一個串列中找出最大值" class="headerlink" title="從一個串列中找出最大值"></a>從一個串列中找出最大值</h2><p>如果在 <code>Java</code> 我們會怎麼做呢?</p>
<ol>
<li>宣個一個變數(max)存放目前的最大值</li>
<li>透過<code>while</code> 或 <code>for</code> 迴圈,將串列中的每個元素跟我們宣告的變數(max)比大小<br>2.1 若元素的值大於max,max的值就改為此元素的值<br>2.2 若元素的值小於或等於max,不做任何事</li>
</ol>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> max = <span class="type">Int</span>.<span class="type">MinValue</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(i <- <span class="type">List</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)){</span><br><span class="line"> <span class="keyword">if</span>(i > max)</span><br><span class="line"> max = i</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p>透過遞迴方式我們會怎麼解決呢?</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">findMax(<span class="type">List</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>))</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">findMax</span></span>(list: <span class="type">List</span>[<span class="type">Int</span>]): <span class="type">Int</span> = {</span><br><span class="line"> list <span class="keyword">match</span>{</span><br><span class="line"> <span class="comment">// 假如是空的串列,我們回傳0</span></span><br><span class="line"> <span class="keyword">case</span> <span class="type">Nil</span> => <span class="number">0</span></span><br><span class="line"> <span class="comment">// 假如只有一個元素的串列,那最大值就為該元素</span></span><br><span class="line"> <span class="keyword">case</span> h :: <span class="type">Nil</span> => h</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 主要邏輯</span></span><br><span class="line"> <span class="keyword">case</span> h :: t => <span class="type">Math</span>.max(h, findMax(t))</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<ul>
<li>在迴圈版本中,逐一每個元素跟某一個mutable變數比大小。</li>
<li>在迴遞版本中,第一個元素跟去除第一個元素的串列的最大值比大小。</li>
</ul>
<p>迴遞的寫法更是簡潔和表達出整個程式主要邏輯,我們再來多試看看幾個題目。</p>
<h2 id="從一個串列中找出最小值"><a href="#從一個串列中找出最小值" class="headerlink" title="從一個串列中找出最小值"></a>從一個串列中找出最小值</h2><p>做法跟找出最大值類似,第一個元素跟去除第一個元素的串列的最小值比大小。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">findMin(<span class="type">List</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>))</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">findMin</span></span>(list: <span class="type">List</span>[<span class="type">Int</span>]): <span class="type">Int</span> = {</span><br><span class="line"> list <span class="keyword">match</span>{</span><br><span class="line"> <span class="comment">// 假如是空的串列,我們回傳0</span></span><br><span class="line"> <span class="keyword">case</span> <span class="type">Nil</span> => <span class="number">0</span></span><br><span class="line"> <span class="comment">// 假如只有一個元素的串列,那最小值就為該元素</span></span><br><span class="line"> <span class="keyword">case</span> h :: <span class="type">Nil</span> => h</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 主要邏輯</span></span><br><span class="line"> <span class="keyword">case</span> h :: t => <span class="type">Math</span>.min(h, findMin(t))</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="檢查一個串列中是否存在某個特定值"><a href="#檢查一個串列中是否存在某個特定值" class="headerlink" title="檢查一個串列中是否存在某個特定值"></a>檢查一個串列中是否存在某個特定值</h2><p>檢查第一個元素是否等於目標值或是去除第一個元素的串列有目標值</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">find(<span class="type">List</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>), <span class="number">5</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">find</span></span>(list: <span class="type">List</span>[<span class="type">Int</span>], target: <span class="type">Int</span>): <span class="type">Boolean</span> = {</span><br><span class="line"> list <span class="keyword">match</span>{</span><br><span class="line"> <span class="comment">// 假如是空的串列,回傳false</span></span><br><span class="line"> <span class="keyword">case</span> <span class="type">Nil</span> => <span class="literal">false</span></span><br><span class="line"> <span class="comment">// 假如只有一個元素的串列,而且該元素等於target,回傳true</span></span><br><span class="line"> <span class="keyword">case</span> h :: <span class="type">Nil</span> <span class="keyword">if</span> (h == target) => <span class="literal">true</span></span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 主要邏輯</span></span><br><span class="line"> <span class="keyword">case</span> h :: t => (h == target) || find(t, target)</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="反轉一個字串"><a href="#反轉一個字串" class="headerlink" title="反轉一個字串"></a>反轉一個字串</h2><p>先反轉去除第一個字元的串列,之後再將第一字元放在最後面</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">reverse(<span class="string">"I should learn scala seriously!"</span>.toList)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">reverse</span></span>(list: <span class="type">List</span>[<span class="type">Char</span>]): <span class="type">String</span> = {</span><br><span class="line"> list <span class="keyword">match</span> {</span><br><span class="line"> <span class="comment">// 假如是空的串列,回傳false</span></span><br><span class="line"> <span class="keyword">case</span> <span class="type">Nil</span> => <span class="string">""</span></span><br><span class="line"> <span class="comment">// 假如只有一個元素的串列,回傳該元素</span></span><br><span class="line"> <span class="keyword">case</span> h :: <span class="type">Nil</span> => h.toString</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 主要邏輯</span></span><br><span class="line"> <span class="keyword">case</span> h :: t => reverse(t) + h</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="判斷一個字串是否為另外一個字串的子字串"><a href="#判斷一個字串是否為另外一個字串的子字串" class="headerlink" title="判斷一個字串是否為另外一個字串的子字串"></a>判斷一個字串是否為另外一個字串的子字串</h2><p>子字串的定義:字數,內容和順序需要符合,空字串為任何字串的子字串<br>例如:</p>
<ul>
<li>“abc” 為 “XXXYYYabc”的子字串</li>
<li>“XXXY” 為 “XXXYYYabc”的子字串</li>
<li>“” 為 “XXXYYYabc”的子字串</li>
<li>“ABC” 不為 “XXXYYYabc”的子字串</li>
<li>“QQWW” 不為 “XXXYYYabc”的子字串</li>
<li>“XXXaYYY” 不為 “XXXYYYabc”的子字串</li>
</ul>
<p>先比較主要字串和子字串的第一個字母是否一樣,</p>
<ul>
<li>若一樣則這兩個字串去除第一個字母繼續比</li>
<li>若不一樣,主要字串去除第一個字母和子字串繼續比</li>
</ul>
<p>例如:<br>主要字串: “abcdefghi”<br>子字串: “abc”<br>檢查主要字串前三個字母(abc)是否和子字串(abc)一樣,若一樣就回傳<code>true</code></p>
<p>主要字串: “abcdefghi”<br>子字串: “defgh”<br>檢查主要字串前五個字母(abcde)是否和子字串(defgh)一樣,若不一樣,<br>則 “bcdefghi” 和 “defgh” 繼續比</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">println(isSubString(<span class="string">"I should learn scala seriously!"</span>.toList, <span class="string">"scala"</span>.toList))</span><br><span class="line">println(isSubString(<span class="string">"I should learn scala seriously!"</span>.toList, <span class="string">"XXOO"</span>.toList))</span><br><span class="line">println(isSubString(<span class="string">"I should learn scala seriously!"</span>.toList, <span class="string">"scaxxyyla"</span>.toList))</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">isSubString</span></span>(original: <span class="type">List</span>[<span class="type">Char</span>], target: <span class="type">List</span>[<span class="type">Char</span>]): <span class="type">Boolean</span> = {</span><br><span class="line"> (original, target) <span class="keyword">match</span> {</span><br><span class="line"> <span class="keyword">case</span> (<span class="type">Nil</span>, _) => <span class="literal">false</span></span><br><span class="line"> <span class="keyword">case</span> (_, <span class="type">Nil</span>) => <span class="literal">true</span></span><br><span class="line"> <span class="keyword">case</span> (o :: <span class="type">Nil</span>, t :: <span class="type">Nil</span>) <span class="keyword">if</span> (o == t) => <span class="literal">true</span></span><br><span class="line"> <span class="keyword">case</span> (o :: <span class="type">Nil</span>, t :: <span class="type">Nil</span>) <span class="keyword">if</span> (o != t) => <span class="literal">false</span></span><br><span class="line"> <span class="keyword">case</span> (o, t) <span class="keyword">if</span> (o.take(t.length) == t) => <span class="literal">true</span></span><br><span class="line"> <span class="keyword">case</span> (oh :: ot, t) => isSubString(ot, t)</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="將一個串列由小排到大"><a href="#將一個串列由小排到大" class="headerlink" title="將一個串列由小排到大"></a>將一個串列由小排到大</h2><p>我們來實作<a href="https://zh.wikipedia.org/wiki/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F" target="_blank" rel="noopener">Quicksort</a></p>
<ol>
<li>從數列中挑出一個元素,稱為 “基準”(pivot)。</li>
<li>重新排序數列,所有比基準值小的元素擺放在基準前面,所有比基準值大的元素擺在基準後面(相同的數可以到任一邊)。在這個分割結束之後,該基準就處於數列的中間位置。這個稱為分割(partition)操作。</li>
<li>遞迴地(recursively)把小於基準值元素的子數列和大於基準值元素的子數列排序。</li>
</ol>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">quicksort(<span class="type">List</span>(<span class="number">4</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">9</span>, <span class="number">10</span>))</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">quicksort</span></span>(list: <span class="type">List</span>[<span class="type">Int</span>]): <span class="type">List</span>[<span class="type">Int</span>] = {</span><br><span class="line"> list <span class="keyword">match</span> {</span><br><span class="line"> <span class="keyword">case</span> <span class="type">Nil</span> => <span class="type">Nil</span></span><br><span class="line"> <span class="keyword">case</span> h :: <span class="type">Nil</span> => <span class="type">List</span>(h)</span><br><span class="line"> <span class="keyword">case</span> h :: t => quicksort(t.filter(_ <= h)) ::: h :: quicksort(t.filter(_ > h))</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h2 id="寫出費氏數列"><a href="#寫出費氏數列" class="headerlink" title="寫出費氏數列"></a>寫出費氏數列</h2><p>何謂費氏數列:<a href="https://zh.wikipedia.org/wiki/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97" target="_blank" rel="noopener">費氏數列</a></p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">fib(<span class="number">6</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fib</span></span>(n: <span class="type">Int</span>): <span class="type">Int</span> = {</span><br><span class="line"> n <span class="keyword">match</span> {</span><br><span class="line"> <span class="keyword">case</span> <span class="number">0</span> => <span class="number">0</span></span><br><span class="line"> <span class="keyword">case</span> <span class="number">1</span> => <span class="number">1</span></span><br><span class="line"> <span class="keyword">case</span> _ => fib(n - <span class="number">1</span>) + fib(n - <span class="number">2</span>)</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p>經過幾次的練習,我們應該大概可以慢慢掌握到怎麼運用遞迴來達到迴圈目的。</p>
<ol>
<li>先把主要邏輯寫出來</li>
<li>再把邊界條件設好,沒有邊界條件就會無窮的跑下去…<br>遞迴主要是透過自我呼叫,把每一步的狀態放在 <code>stack</code>,等走到邊界回傳邊界值或完成邊界條件後,再回溯回去。</li>
</ol>
<p>把問題透過<a href="https://zh.wikipedia.org/wiki/%E5%88%86%E6%B2%BB%E6%B3%95" target="_blank" rel="noopener">Divide and conquer</a>方式,<br>大問題分解成數個小問題,若小問題規模較小且易於解決時,則直接解。否則,遞歸地解決各小問題。<br>最後再將每個小問題的結果逐一合併起來。</p>
<p>遞迴的寫法很簡潔,但是最大的問題是效能不好和容易 <code>Stack Overflow</code>。<br>主要原因是會去嘗試走所有可能的路徑而且把每一個狀態放在stack,當狀態一多就爆了。<br>去嘗試走所有可能的路徑也是造成效能不好的原因。</p>
<p>假如:</p>
<ol>
<li>去嘗試走所有可能的路徑不多,但是每一個步計算很花時間,遞迴容易轉換成非同步程式。</li>
</ol>
<p>以排序為例,一個串列數量小於一千,我們可以使用<a href="https://zh.wikipedia.org/wiki/%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F" target="_blank" rel="noopener">Insertion Sort</a>;大於一千改使用Quicksort:</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sort</span></span>(list: <span class="type">List</span>[<span class="type">Int</span>]): <span class="type">List</span>[<span class="type">Int</span>] = {</span><br><span class="line"> <span class="keyword">if</span>(list.length < <span class="number">1000</span>){</span><br><span class="line"> <span class="comment">// 需要大量時間計算才可以得出結果</span></span><br><span class="line"> insertionSort(list)</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">else</span>{</span><br><span class="line"> list <span class="keyword">match</span> {</span><br><span class="line"> <span class="keyword">case</span> <span class="type">Nil</span> => <span class="type">Nil</span></span><br><span class="line"> <span class="keyword">case</span> h :: <span class="type">Nil</span> => <span class="type">List</span>(h)</span><br><span class="line"> <span class="keyword">case</span> h :: t => sort(t.filter(_ <= h)) ::: h :: sort(t.filter(_ > h))</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p>我們可以輕易將它轉換成非同步程式。<br><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sort</span></span>(list: <span class="type">List</span>[<span class="type">Int</span>]): <span class="type">Future</span>[<span class="type">List</span>[<span class="type">Int</span>]] = {</span><br><span class="line"> <span class="keyword">if</span>(list.length < <span class="number">1000</span>){</span><br><span class="line"> <span class="comment">// 需要大量時間計算才可以得出結果 </span></span><br><span class="line"> <span class="type">Future</span>(insertionSort(list))</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">else</span>{</span><br><span class="line"> list <span class="keyword">match</span> {</span><br><span class="line"> <span class="keyword">case</span> <span class="type">Nil</span> => <span class="type">Future</span>(<span class="type">Nil</span>)</span><br><span class="line"> <span class="keyword">case</span> h :: <span class="type">Nil</span> => <span class="type">Future</span>(<span class="type">List</span>(h))</span><br><span class="line"> <span class="keyword">case</span> h :: t => <span class="type">Future</span>(sort(t.filter(_ <= h)) ::: h :: sort(t.filter(_ > h)))</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure></p>
<p>非遞迴的版本就很難改了,因為主要存在共享的mutable變數,多個thread會共享同一個變數,就需要做同步處理。<br>同步問題沒有小心處理,結果很容易出錯。</p>
<ol>
<li>嘗試走所有可能的路徑很多</li>
</ol>
<p>例如:計算第五十個費氏數列<br>根據計算費氏數列的遞迴公式,<code>n = 50</code> 的樹狀結構會相當大。我們可以透過 <a href="http://localhost:4000/2016/12/09/Scala-Tail-recursion/" target="_blank" rel="noopener">Tail recursion</a> 來解決。<br>把上一個狀態的結果直接當成帶入參數,而不是依賴上一個狀態的結果。</p>
<p>因為 <code>fib(n) = fib(n - 1) + fib(n - 2)</code>,假如可以把 <code>fib(n - 1)</code> 和 <code>fib(n - 2)</code> 當參數帶入,<br>這樣就可以馬上得出 <code>fib(n)</code>,而不是等算完 <code>fib(n - 1)</code> 和 <code>fib(n - 2)</code> 後才可以得出 <code>fib(n)</code>。</p>
<pre><code class="scala"><span class="keyword">import</span> scala.annotation.tailrec
fib(<span class="number">0</span>, <span class="number">1</span>, <span class="number">5</span>)
<span class="meta">@tailrec</span>
<span class="function"><span class="keyword">def</span> <span class="title">fib</span></span>(previous: <span class="type">Int</span>, current: <span class="type">Int</span>, n: <span class="type">Int</span>): <span class="type">Int</span> = {
n <span class="keyword">match</span> {
<span class="keyword">case</span> <span class="number">0</span> => previous
<span class="keyword">case</span> <span class="number">1</span> => current
<span class="keyword">case</span> _ => fib(current, previous + current, n - <span class="number">1</span>)
}
}
</code></pre>
<p>有興趣的讀者可以到 <a href="https://scalataiwan.github.io/ScalaKitchen/recursive.html" target="_blank" rel="noopener">ScalaKitchen</a> 試玩看看,也有提供<a href="https://scalataiwan.github.io/ScalaKitchen/" target="_blank" rel="noopener">中文版本的Scala入門教學</a>。</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="https://pandaforme.github.io/2017/02/15/Scala-Use-Either-Try-to-hand-error/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="pandaforme">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Programming blog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2017/02/15/Scala-Use-Either-Try-to-hand-error/" itemprop="url">
[Scala] Use Either to hand error cases
</a>
</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">Posted on</span>
<time title="Created: 2017-02-15 16:57:00" itemprop="dateCreated datePublished" datetime="2017-02-15T16:57:00+08:00">2017-02-15</time>
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-calendar-check-o"></i>
</span>
<span class="post-meta-item-text">Edited on</span>
<time title="Modified: 2017-02-16 12:08:25" itemprop="dateModified" datetime="2017-02-16T12:08:25+08:00">2017-02-16</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">In</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Scala/" itemprop="url" rel="index"><span itemprop="name">Scala</span></a></span>
</span>
<span class="post-comments-count">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-comment-o"></i>
</span>
<a href="/2017/02/15/Scala-Use-Either-Try-to-hand-error/#comments" itemprop="discussionUrl">
<span class="post-comments-count disqus-comment-count"
data-disqus-identifier="2017/02/15/Scala-Use-Either-Try-to-hand-error/" itemprop="commentCount"></span>
</a>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>在OOP的語言中,我們exception來表達程式錯誤或是系統crash.Exception又可以分為<code>Checked Exception</code> 和 <code>UnChecked Excpetion</code>.</p>
<ul>
<li><p>Checked Exception: 會將要丟出的excpetion寫在function的signature.<br>例如:</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">interface <span class="type">Foo</span>() <span class="keyword">throws</span> <span class="type">XXXException</span>, <span class="type">YYYException</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>UnChecked Excpetion: 要丟出的excpetion不會寫在function的signature,呼叫function的人需要知道有exception要處理.</p>
</li>
</ul>
<p>Checked Exception會違反<a href="https://en.wikipedia.org/wiki/Open/closed_principle" target="_blank" rel="noopener">Open/Closed Principle</a>,當有新增丟出的excpetion,需要修改interface signature;UnChecked Excpetion則是需要知道有哪些exception需要處理.</p>
<p>這兩種exception孰好孰壞,在 <code>Clean code: a handbook of agile software craftsmanship, Robert C. Martin</code> 有提到:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">The debate is over. For years Java programmers have debated over the benefits and liabilities of checked exceptions. When checked exceptions were introduced in the first version of Java, they seemed like a great idea. The signature of every method would list all of the exceptions that it could pass to its caller. Moreover, these exceptions were part of the type</span><br><span class="line">of the method. Your code literally wouldn't compile if the signature didn't match what your code could do.</span><br><span class="line"></span><br><span class="line">At the time, we thought that checked exceptions were a great idea; and yes, they can yield some benefit. However, it is clear now that they aren't necessary for the production of robust software. C# doesn't have checked exceptions, and despite valiant attempts, C++ doesn't either. Neither do Python or Ruby. Yet it is possible to write robust software in all of these languages. Because that is the case, we have to decide—really—whether checked exceptions are worth their price.</span><br><span class="line"></span><br><span class="line">Checked exceptions can sometimes be useful if you are writing a critical library: You must catch them. But in general application development the dependency costs outweigh the benefits</span><br></pre></td></tr></table></figure></p>
<p>在Java中建議使用UnChecked Excpetion,但是這會導致另外一個災難…</p>
<ol>
<li>呼叫者不知道會丟出exception</li>
<li>呼叫者不知道有哪些excpetion要處理,當call chain很深的時候更是糟糕…</li>
<li>到處充滿了 <code>try{...} catch{...}</code></li>
</ol>
<p>相信使用Java開發的工程師應該感觸良多,尤其是在維護舊專案.一個call chain長達十幾層,每一層丟的excpetion都不一樣,有些層會處理exception,有些又不會,最後的大絕招就是每一層都加 <code>try{...} catch{...}</code>.</p>
<p>例外處理在OOP是一個很重要的議題,沒有謹慎處理很容易造成維護困難和發生問題不容易找到問題點.<br>因為Exception是有side effect,在FP是不被准許的.所以在pure FP程式中是看不到excpetion和 <code>try{...} catch{...}</code>.</p>
<h1 id="Either"><a href="#Either" class="headerlink" title="Either"></a>Either</h1><p>我們可以透過 <code>Either</code> 來達成,<code>Left</code> 放錯誤的物件,<code>Right</code> 放正確的物件:<br><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">sealed</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Either</span>[<span class="type">A</span>, <span class="type">B</span>]</span></span><br><span class="line"><span class="class"><span class="title">final</span> <span class="title">case</span> <span class="title">class</span> <span class="title">Left</span>[+<span class="type">A</span>, +<span class="type">B</span>](<span class="params">a: <span class="type">A</span></span>) <span class="keyword">extends</span> <span class="title">Either</span>[<span class="type">A</span>, <span class="type">B</span>]</span></span><br><span class="line"><span class="class"><span class="title">final</span> <span class="title">case</span> <span class="title">class</span> <span class="title">Right</span>[+<span class="type">A</span>, +<span class="type">B</span>](<span class="params">b: <span class="type">B</span></span>) <span class="keyword">extends</span> <span class="title">Either</span>[<span class="type">A</span>, <span class="type">B</span>]</span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"><span class="title">//</span> <span class="title">for</span> <span class="title">exmple</span></span></span><br><span class="line"><span class="class"><span class="title">type</span> <span class="title">Error</span> </span>= <span class="type">String</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">val</span> result = <span class="type">Right</span>[<span class="type">Error</span>, <span class="type">Int</span>](<span class="number">123</span>)</span><br><span class="line"><span class="keyword">val</span> error = <span class="type">Left</span>[<span class="type">Error</span>, <span class="type">Int</span>](<span class="string">"Something wrong!!!"</span>)</span><br></pre></td></tr></table></figure></p>
<p>我們可以把正確的結果或錯誤放到 <code>Either</code> 這個容器,呼叫者可以清楚知道有需要處理錯誤情況,再來程式碼不再到處充斥 <code>try{...} catch{...}</code>.</p>
<p>我們使用四則運算來當範例,如何使用 <code>Either</code><br><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">div</span></span>(a: <span class="type">Double</span>, b: <span class="type">Double</span>): <span class="type">Either</span>[<span class="type">String</span>, <span class="type">Double</span>] = {</span><br><span class="line"> <span class="keyword">if</span>(b == <span class="number">0</span>) <span class="type">Left</span>[<span class="type">String</span>, <span class="type">Double</span>](<span class="string">"Can't divide by 0 !!!"</span>)</span><br><span class="line"> <span class="keyword">else</span> <span class="type">Right</span>[<span class="type">String</span>, <span class="type">Double</span>](a / b)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span></span>(a: <span class="type">Double</span>, b: <span class="type">Double</span>): <span class="type">Either</span>[<span class="type">String</span>, <span class="type">Double</span>] = {</span><br><span class="line"> <span class="type">Right</span>[<span class="type">String</span>, <span class="type">Double</span>](a + b)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">minus</span></span>(a: <span class="type">Double</span>, b: <span class="type">Double</span>): <span class="type">Either</span>[<span class="type">String</span>, <span class="type">Double</span>] = {</span><br><span class="line"> <span class="type">Right</span>[<span class="type">String</span>, <span class="type">Double</span>](a - b)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mul</span></span>(a: <span class="type">Double</span>, b: <span class="type">Double</span>): <span class="type">Either</span>[<span class="type">String</span>, <span class="type">Double</span>] = {</span><br><span class="line"> <span class="type">Right</span>[<span class="type">String</span>, <span class="type">Double</span>](a * b)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// ((((1 + 2) * 3) / 4) - 5)</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">val</span> result = <span class="keyword">for</span> {</span><br><span class="line"> r1 <- add(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line"> r2 <- mul(r1, <span class="number">3</span>)</span><br><span class="line"> r3 <- div(r2, <span class="number">4</span>)</span><br><span class="line"> r4 <- minus(r3, <span class="number">5</span>)</span><br><span class="line">} <span class="keyword">yield</span> {</span><br><span class="line"> r4</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// result: scala.util.Either[String,Double] = Right(-2.75)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// ((((1 + 2) * 3) / 0) - 5)</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">val</span> result = <span class="keyword">for</span> {</span><br><span class="line"> r1 <- add(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line"> r2 <- mul(r1, <span class="number">3</span>)</span><br><span class="line"> r3 <- div(r2, <span class="number">0</span>)</span><br><span class="line"> r4 <- minus(r3, <span class="number">5</span>)</span><br><span class="line">} <span class="keyword">yield</span> {</span><br><span class="line"> r4</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// result: scala.util.Either[String,Double] = Left(Can't divide by 0 !!!)</span></span><br></pre></td></tr></table></figure></p>
<p>根據上面簡單的範例,這樣的寫法很明顯優於傳統OOP用excpetion來處理錯誤:</p>
<ul>
<li>不再有 <code>try{...} catch{...}</code> 充斥在每個地方.</li>
<li>呼叫者可以根據fucntion signature知道是否會產生錯誤.</li>
<li>更可以專心在商業邏輯,而不用花多餘的心力在處理例外.</li>
</ul>
<h1 id="Try"><a href="#Try" class="headerlink" title="Try"></a>Try</h1><figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">sealed</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Try</span>[+<span class="type">T</span>]</span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"><span class="title">final</span> <span class="title">case</span> <span class="title">class</span> <span class="title">Failure</span>[+<span class="type">T</span>](<span class="params">exception: <span class="type">Throwable</span></span>) <span class="keyword">extends</span> <span class="title">Try</span>[<span class="type">T</span>] </span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"><span class="title">final</span> <span class="title">case</span> <span class="title">class</span> <span class="title">Success</span>[+<span class="type">T</span>](<span class="params">value: <span class="type">T</span></span>) <span class="keyword">extends</span> <span class="title">Try</span>[<span class="type">T</span>]</span></span><br></pre></td></tr></table></figure>
<p><code>Try</code> 也是類似於 <code>Either</code> 的context,有興趣的讀者可以試用看看.在實務上大部分都採用 <code>Either</code>,不採用 <code>Try</code>的原因是:</p>
<ul>
<li>沒有辦法對exception做 <code>exhaustive pattern match</code>,當是Failure的時候,呼叫者不知道有哪些exception會丟出,只知道會丟出一個 <code>Throwable class</code>.</li>
</ul>
<p>使用 <code>Either</code> 我們可以自訂Error type,當失敗時候就可以對Error type做 <code>exhaustive pattern match</code>,依據不同的錯誤做不同的處理.</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="https://pandaforme.github.io/2016/12/20/Scala-How-to-use-Option-correctly/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="pandaforme">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Programming blog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2016/12/20/Scala-How-to-use-Option-correctly/" itemprop="url">