Skip to Content
Javaによる関数型プログラミング ―Java 8ラムダ式とStream
book

Javaによる関数型プログラミング ―Java 8ラムダ式とStream

by Venkat Subramaniam, 株式会社プログラミングシステム社
October 2014
Intermediate to advanced
236 pages
2h 34m
Japanese
O'Reilly Japan, Inc.
Content preview from Javaによる関数型プログラミング ―Java 8ラムダ式とStream

7章再帰の最適化

難しい問題は、それを解くために適切かつ必要なところまで分割しなさい。

――René Descartes

再帰は魅力的で強力な問題解決方法です。再帰はとても表現力に富んでいます。ある問題自体の解決方法を、その問題の部分的な問題にも適用するような解決方法を提供します。このアプローチは「分割統治法(divide and conquer)」と呼ばれます。地図上の最短距離を求める場合や、最小コストまたは最大の利益を計算する場合、無駄を削減する場合など、様々なアプリケーションに使われています。

今日使われているほとんどのプログラミング言語が再帰をサポートしています。ただ、再帰が本当に役に立つような問題は非常に大きな問題であることが多く、単純な実装では残念ながらすぐにスタックオーバーフローが発生してしまいます。そこで本章では、大きな問題の再帰処理を可能とする末尾呼び出し最適化(tail-call optimization、TCO)を説明します。最後に、問題の解法がその部分問題の解法と重なるような再帰問題を紹介し、メモ化を使ってその解決を高速にする方法を説明します。

7.1 末尾呼び出し最適化を使う

再帰を使う上で最も高いハードルは、巨大な入力値によるスタックオーバーフローのリスクです。しかし、末尾呼び出し最適化(TCO)という優れたテクニックがこの心配の種を取り除きます。末尾呼び出しとは、最後の処理が自身の呼び出しとなるような再帰呼び出しのことをいいます。これは、自身への呼び出しの後にその結果を使って処理を続ける通常の再帰とは異なります。TCOは通常の再帰呼び出しを末尾呼び出しに変えて、大きな入力値でも再帰を実用的なものにします。

JavaはTCOをコンパイラレベルで直接サポートしていませんが、ラムダ式を使って数行で実装できます。このソリューションはトランポリン ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

リーダーの作法 ―ささいなことをていねいに

リーダーの作法 ―ささいなことをていねいに

Michael Lopp, 和智 右桂
コンピュータビジョンのための実践機械学習 ―モデルアーキテクチャからMLOpsまで

コンピュータビジョンのための実践機械学習 ―モデルアーキテクチャからMLOpsまで

Valliappa Lakshmanan, Martin Görner, Ryan Gillard, 大山 匠, 松田 晃一

Publisher Resources

ISBN: 9784873117041Other