Share to: share facebook share twitter share wa share telegram print page

宣言型プログラミング

宣言型プログラミング: Declarative programming)は、数理論理学的な性質を表わしている総称的なプログラミングパラダイムである。の計算構造を、主に表示的意味論下のロジックで表現する構文にされることが多く、枠外の副作用を伴なう制御フロー自由変数の多用などは排除されるようになる[1]。計算構造は演繹的に組み立てられることが多い。命令型プログラミングと対をなしてのプログラミング言語の分類用語としても扱われている。[注釈 1]}

宣言型言語は、what the program must accomplish(何をなすべきか)方針で、副作用を排除した式や純粋関数の実装に努める[2]。これは命令型言語の、how to accomplish it(どうなすべきか)方針で、副作用を前提にした操作的意味論下のアルゴリズム実装とよく対比される[3]

宣言的パラダイムは、関数型論理型データフローなどを包括し、データベース問い合わせ言語マークアップ言語ドメイン固有言語構成管理正規表現などにも言及されており、並行計算との親和性も特筆されている[4]

概要

宣言型プログラミングは、現行式枠外の外部状態への代入コマンド、および外部状態の現行式への影響(副作用)といった命令的な性質を持たないパラダイムとして定義されている。命令的性質のステートメントに対して、宣言的なプログラムの基本はとされる。

コマンドと副作用を持つ命令的なオペレータ(手続き関数サブルーチン)は、計算内容のリスト化とステップ単位解釈が必要になるので、これがhow to accomplish it(どうなすべきか)とされる。

コマンドと副作用を持たない宣言的なオペレータは、その定義だけで計算内容を把握できるので、これがwhat to accomplish it(何をなすべきか)とされる。命令的オペレータを用いずに、宣言的オペレータを用いることが即ち宣言的なプログラムになる[2][5]。式はオペレータオペランド、他の式、再帰式などの組み合わせになる。

宣言的パラダイムにあるべき特徴は以下のようになる。

  1. 計算を主に表示的意味論で記述する高水準言語
  2. 参照透過を担保できるように表現された副作用
  3. 計算そのものを計算対象にできるという高階なプログラム
  4. 数理論理学に準拠したプログラム[6]

宣言的オペレータの性質である参照透過性は、同じ引数に対するオペレータの動作と返り値が不変であることを意味する[7]

式は単体で評価されるほか、引数に適用されて評価値(返り値)になる。式はほかへの引数にもなり、高階論理の式は他の式を引数にする。微分導関数と同様に、式の返り値を式にすることもできる。引数や返り値にもできる式は、第一級オブジェクトとされる。

SQLのクエリは「どのようなデータが欲しいか」を宣言し、「いかにしてデータベースにアクセスするか」という命令・手続きには関与しない。関数型言語の多くは、コマンドと副作用の取り扱いも許容している命令型と宣言型の折衷になっている。純粋関数型言語は宣言的に徹しており、プログラム正当性形式的検証を可能にしている[注釈 2]。加えて副作用は常に失敗する可能性と隣り合わせだが、宣言型プログラミングでは副作用の使用を制限し、純粋なコードから分離することで、失敗への対処漏れがあったとしても問題点を突き止めやすくなるというメリットもある。 宣言型の最大の特徴である形式的検証に対して、命令型ではクラスオブジェクトを宣言的フレームワークに内包して局面的な宣言的オペレータにしてその動作を検証することがある。JavaテストフレームワークJUnitなどが例である。

宣言型は並行プログラミングとの親和性が高いことも特筆される。これはセマフォミューテックスや読み書きロックなどを駆使して同期的な並行性を実現することが多い命令型に対するアドバンテージである。宣言型は、式としてのプロセスを代数として扱えるので、その代数を他のプロセスへの引数としてのメッセージにしつつ、部分計算や評価戦略を応用しての非同期な並行性を実現できる。

利点

計算式の抽象値化

参照透過な計算式は、時と場所に左右されない抽象値にもなる[8]。いつどこで計算されても同じ引数に対して同じ結果が返るならば、あえて計算しないままにしておいての抽象値として扱おう[9]とするのが宣言型のアプローチである。この概念の実装例はクロージャである。クロージャは、他の式や関数の束縛変数にされることが前提のレキシカルスコープ基準の無名関数である。

もう一つの実装例は、宣言的な関数オブジェクトである。そこでは処理+返り値の青写真になる不変部分と、引数で決定される処理+返り値の可変部分が明確に分離されている。宣言型は、段階的詳細化した各要素を不変部分と可変部分の構成体にすることをアプローチする。これに準拠した技術の仮想DOMは、XMLHTML文書を変換したツリー構造の各ノードを、不変+可変構成の宣言的オブジェクトに再変換している[10]。その不変部分は不変状態と同義になり、しばしばイミュータブルの概念で説明される。

計算の最適化

宣言的UIは、命令的オブジェクト指向UI(OOUI)と対比されて一長一短があるが、軽量さと再描画速度での利点が挙げられやすい。徹底的な遅延結合を旨とするOOUIでは、何かの更新イベントが発生する度に、UI要素間のメソッドの呼び合い(メッセージ)とUI要素それぞれの総合的な再解釈が行われがちである。宣言的UIでは、各UI要素は青写真としての不変部分を持ち、可変部分に適用される引数はメモ化されていて、同じ引数が渡された場合は計算スキップされる[11]。更新イベントは各UI要素への引数に変換されて、差異引数を渡されたUI要素だけが再解釈されるので再描画計算量は軽減されやすい[12]。そこでは以前の描画状態を鑑みる必要はない[13]。このようにしなくていい計算を明確化して全体の最適化に繋げるのが宣言型のアプローチである。

また、宣言的構造は不変部分と可変部分が明確に区分けされるので、何もかもが遅延結合のミュータブルになりがちなオブジェクト/メッセージ構造よりも平易かつ明瞭になるという利点もある。

未来要素を内包した計算

参照透過な計算式は、次以降の式で確定される未来要素(前方参照遅延評価)を残したままの結果値を返すこともできる。その結果値とは、次以降の式で引数が与えられることを前提にした第一級関数になる。それは次以降の式で確定される前方参照要素を残したままの未評価式であり、次の式の束縛変数にされるか、式枠外の変数に束縛されて保存されるなどして、次以降の式から渡される引数によって最終的な結果値になる。

宣言型は、次以降の式で確定される前方参照要素を残したままの抽象値の取り扱いをアプローチする。その実装例にはFutureなどがある。それらを高度に応用した数学理論が並行プログラミング分野のアクターモデルプロセス代数である。

また宣言型は、前方参照要素を残した抽象値同士をそのまま計算することもアプローチする。そこでは部分評価や部分計算などの数学理論が用いられる。制約プログラミングはそれらに準拠している。

副作用を排した純粋な計算

参照透過な計算式では、式枠外の状態(データなど)は完全に無視される。計算式が外部状態を扱えるのは、それが引数として渡された時のみである。その引数を加工した返り値は、そのままではただのデータであり、それが外部状態に反映されるかは式枠外のプロセスの担当になる。また、参照透過な計算式は、式枠内にも可変の状態(データなど)を持つことはできない。可変の内部状態に依存した計算ではその冪等性が失われるからである。これらの性質は純粋関数とも呼ばれる。

例として、押すたびにオン/オフが切り替わる電気スイッチ・オペレータがあるとする。命令的オペレータでは現状のオン/オフを状態保存できるので、別途変数を参照するという形式で、オペレータとオン/オフ状態をユニット実装できる。これに対して宣言的オペレータでは、引数として渡されたオン/オフ状態を参照するという形式になり、そこではオペレータとオン/オフ状態を別々に扱うことになる。これだけだと宣言的の方が、ただ煩雑に見える。しかしその”状態”に、オン/オフだけでなく昼夜の区別やアンペア許容やその他諸々の要素が加わっていくと、そうではなくなるというのが宣言型のアプローチである。

その時に必要な対象値と”状態”をセットにしての純粋関数を実現する手法としては、部分構造論理由来のサブ構造型システムと、圏論由来のモナドなどがある。

状態の分離

宣言型プログラミングでは宣言部分と状態を分離できる。なぜなら宣言部分ではあるべき状態を宣言するため、その前にどうなっていたかは無関係であるからである。例えば「廊下の電気はONである」と宣言した場合、現在の廊下の電気がONであれOFFであれ、(宣言された)なるべき状態はONであり、現在の状態とは無関係である。すなわち宣言型プログラミングでは時間と共にどう変わるか(=状態)を宣言部分で考える必要がなくなる[14]

もし命令型プログラミングを用いて「廊下のスイッチを押す」という命令をコーディングして廊下の電気を制御した場合、実行後の電気がONかOFFかは現在の値に依存する。ゆえに出力を予測するには状態の履歴を知っている必要がある。そして状態の履歴を知るためには、状態を操作しうる他のコードを把握し、その操作履歴を知る必要がある。ON/OFFの2状態ならまだしも、多数の状態が相互作用する多数のオブジェクトから操作される場合、状態の予測は著しく困難になり、デバッグを含めたプログラミングが難しくなりうる。一方で宣言型プログラミングの場合、宣言部分は状態履歴を必要としないため、宣言部分の出力は常に明確である。

注意点として、状態は分離されているのであり、状態が消滅したわけではない。宣言型プログラミングの場合、light変数にてあるべきライトの状態 "ON"/"OFF" を保持しておき、現在の時刻に基づいてlight変数を切り替え、それが「廊下の電気は{light}である」という宣言に反映されて実際に廊下の電気がONになるというような形になる。light変数という状態は存在しており、これが宣言部分と分離され、宣言部分は最新のlight変数が示す今の電気があるべき状態のみを反映した(過去の電気状態履歴とは無関係な)形になっている。命令的プログラミングで問題となった予測の困難さは、light変数の履歴予測の困難さに分離されている。light変数を誰がいつ操作したかは依然として追跡の難しい問題であるが、宣言部分が分離されたことで問題の所在が限局したものになっている。

宣言型言語の例

宣言型に準拠したプログラミング言語

宣言型に準拠したドメイン固有言語

宣言型を適用したフレームワーク各種

脚注

注釈

  1. ^ ここでは純粋関数を要求しているが、宣言型プログラミングは純粋関数型言語に限定されないことに十分な注意を要す
  2. ^ 副作用を完全に排除してしまうと、大抵の場合はコンピュータ言語として機能しなくなる(画面への表示やファイルなどへの読み書きも副作用とされているので、実行結果を得ることすらできない)ので、参照透過性だけを保証して副作用を許容している。

出典

  1. ^ Lloyd, J.W., Practical Advantages of Declarative Programming 
  2. ^ a b "what declarative programming is. Intuitively, it is programming by defining the what (the results we want to achieve) without explaining the how (the algorithms, etc., needed to achieve the results). " P. Van Roy and S. Haridi (2001). コンピュータプログラミングの概念・技法・モデル. p.117.
  3. ^ declarative language”. FOLDOC (2004年5月17日). 2020年1月26日閲覧。
  4. ^ Sebesta, Robert (2016). Concepts of programming languages. Boston: Pearson. ISBN 978-0-13-394302-3. OCLC 896687896 
  5. ^ 「宣言的記述を行う高水準言語の主要なお題目は『どうやって計算するか(How)ではなく, 何を計算するか(What)を記述する』というものである.」 (近山隆「ソフトウェアの30年とこれから」『コンピュータ ソフトウェア』第31巻第2号、日本ソフトウェア科学会、2014年、9頁、CRID 1390282679715495936doi:10.11309/jssst.31.2_8ISSN 0289-6540 
  6. ^ Chakravarty, Manuel M. T. (14 February 1997). On the Massively Parallel Execution of Declarative Programs (Doctoral dissertation). Technical University of Berlin. 2015年2月26日閲覧In this context, the criterion for calling a programming language declarative is the existence of a clear, mathematically established correspondence between the language and mathematical logic such that a declarative semantics for the language can be based on the model or the proof theory (or both) of the logic.
  7. ^ "We say the operation is declarative if, whenever called with the same arguments, it returns the same results independent of any other computation state." P. Van Roy and S. Haridi (2001). コンピュータプログラミングの概念・技法・モデル. p.113.
  8. ^ 時間軸と何が起きたかを意識せずに宣言的に記述できる sonatard. (2019) 宣言的UI. p.37
  9. ^ Here is the critical thing. We no longer need to think about how our UI changes over time. What happens is, when we get in the data, we show what it should look like. We show what the next state is. And then framework controls how to get from one state into the other. And so now we no longer need to think about it. And that's the critical piece. Leland Richardson (2019-10-24) "Understanding Compose (Android Dev Summit '19)"
  10. ^ "programming concept where an ideal ... representation ... is kept in memory and synced with the “real” DOM by a library ... This approach enables the declarative API ... : You tell React what state you want the UI to be in, and it makes sure the DOM matches that state. This abstracts out the attribute manipulation, event handling ..." React. Virtual DOM and Internals.
  11. ^ "declarative UI ... works by conceptually regenerating the entire screen from scratch, then applying only the necessary changes." Thinking in Compose. Jetpack Compose.
  12. ^ "React provides a declarative API so that you don’t have to worry about exactly what changes on every update." React. Reconciliation.
  13. ^ 前回のViewの状態に依存せずに、最終的に描画されるViewを宣言的に記述できる sonatard. (2019) 宣言的UI. p.37
  14. ^ Here is the critical thing. We no longer need to think about how our UI changes over time. What happens is, when we get in the data, we show what it should look like. We show what the next state is. And then framework controls how to get from one state into the other. And so now we no longer need to think about it. And that's the critical piece. Leland Richardson (2019-10-24) "Understanding Compose (Android Dev Summit '19)"

参考文献

関連項目

外部リンク

Read other articles:

Koordinat: 8°08′23″S 115°06′14″E / 8.139757°S 115.103964°E / -8.139757; 115.103964 SukasadaKecamatanPeta lokasi Kecamatan SukasadaNegara IndonesiaProvinsiBaliKabupatenBulelengPemerintahan • CamatDrs. I Gusti Ngurah SuradnyanaPopulasi • Total76,490 jiwa (2.016)[1] 72,050 jiwa (2.010)[2] jiwaKode pos81161Kode Kemendagri51.08.05 Kode BPS5108050 Luas172,93 km²[1]Desa/kelurahan14 desa 1 Kelurahan[1]Situs…

Theater performed in Chicago, Illinois For the theater building at 175 North State Street built in 1921, see Chicago Theatre. The Chicago Theatre The Auditorium Theatre Theater in Chicago describes not only theater performed in Chicago, Illinois, but also to the movement in Chicago that saw a number of small, meagerly funded companies grow to institutions of national and international significance. Chicago had long been a popular destination for touring productions, as well as original productio…

Зображення варшавської сирени 1659 р. Історія Варшави налічує понад 1400 років. У той час місто перетворилося з кластера сіл до столиці великої європейської держави, Речі Посполитої — і під патронатом її королів, до центру просвітництва та інакше невідомої толерантност

Danish children's illustrator and writer Olsen (right) and Steffen Brandt in 2003. Ib Spang Olsen (11 June 1921 – 15 January 2012) was a Danish writer and illustrator best known to generations of Danes for cartoons and illustrations, many of which appeared in children's publications.[1] Those include a series of nursery rhyme books written by Halfdan Rasmussen, including Halfdans ABC.[1][2] He also wrote his own children's books, such as the whimsical tale of the season…

Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Cet article ne cite pas suffisamment ses sources (février 2023). Si vous disposez d'ouvrages ou d'articles de référence ou si vous connaissez des sites web de qualité traitant du thème abordé ici, merci de compléter l'article en donnant les références utiles à sa vérifiabilité et en les liant à la section « Notes et références » En pratique : Quelles sources sont attendues ? Comm…

Camera dei deputati L’Aula parlamentare della Camera dei deputati, rappresentata su un francobollo Nome originale(RO) Camera Deputaților Stato Romania TipoCamera bassa del Parlamento della Romania Istituito1862 PresidenteAlfred Simonis (PSD)(ad interim)(dal 14 giugno 2023) Vicepresidenti Ana Maria Cătăuță (PSD) Daniel Suciu (PSD) Florin Claudiu Roman (PNL) Mădălina Prună (USR) Ultima elezione6 dicembre 2020 Prossima elezione2024 Numero di membri330 Durata mandato4 anni Gruppi…

Ecuadorian footballer (born 1986) For the Columbian footballer forward, see Diego Calderón (Colombian footballer). In this Spanish name, the first or paternal surname is Calderón and the second or maternal family name is Espinoza. Diego Calderón Calderón with Barcelona SC in 2015Personal informationFull name Diego Armando Calderón Espinoza[1]Date of birth (1986-10-26) October 26, 1986 (age 37)Place of birth Quito, EcuadorHeight 1.80 m (5 ft 11 in)Position…

Subgenus of flowering plants Arisaema sect. Pistillata Arisaema serratum Scientific classification Kingdom: Plantae Clade: Tracheophytes Clade: Angiosperms Clade: Monocots Order: Alismatales Family: Araceae Genus: Arisaema Section: Arisaema sect. Pistillata(Engler) Nakai 1929 Type species Arisaema serratum Species See text Arisaema section Pistillata is a section of the genus Arisaema.[1] Description Plants in this section have paradioecious tubers with one to two 3 foliate or pedately m…

The Accidental PervertPromotional artwork for the playWritten byAndrew GoffmanCharactersAndrewDate premieredNovember 16, 2005Place premiered45th Street Theater New York, NYOriginal languageEnglishGenreComedy, MonodramaSettingA room The Accidental Pervert is a universally themed play written and performed by Andrew Goffman and directed by Charles Messina. Story An 11-year-old boy finds his father's collection of X-rated videos hidden in a bedroom closet and subsequently develops an addiction to p…

Australian band The Black SorrowsOriginMelbourne, Victoria, AustraliaGenresBlues, rock, R&B, soul, zydecoYears active1983 (1983)–presentLabelsSpirit, Camel, CBS, Mushroom, Epic, Liberation Blue, Rajon, ABC/WarnerMembers Joe Camilleri Claude Carranza Angus Burchall Mark Gray John McAll Past memberssee Members list belowWebsitetheblacksorrows.com.au The Black Sorrows are an Australian blues rock band formed in 1983 by mainstay vocalist Joe Camilleri (ex-Jo Jo Zep & The Falcons), who…

Este artigo ou secção contém uma lista de referências no fim do texto, mas as suas fontes não são claras porque não são citadas no corpo do artigo, o que compromete a confiabilidade das informações. Ajude a melhorar este artigo inserindo citações no corpo do artigo. (Setembro de 2021) Guido Crepax Nascimento 15 de julho de 1933 Morte 31 de julho de 2003 Trabalhos de destaque Valentina Guido Crepax (n. Guido Crepas, Milão; 15 de julho de 1933 - 31 de julho de 2003) foi um artis…

Form of reasoning Deductive reasoning is the mental process of drawing deductive inferences. An inference is deductively valid if its conclusion follows logically from its premises, i.e. it is impossible for the premises to be true and the conclusion to be false. For example, the inference from the premises all men are mortal and Socrates is a man to the conclusion Socrates is mortal is deductively valid. An argument is sound if it is valid and all its premises are true. Some theorists define de…

Home video game console N64 redirects here. For other uses, see N64 (disambiguation). Nintendo 64A black Nintendo 64 (right) and light gray Nintendo 64 controllerAlso known as Project Reality (code name) Ultra 64 (planned product name) Hyundai Comboy 64 (South Korea) DeveloperNintendo IRDManufacturerNintendoTypeHome video game consoleGenerationFifthRelease dateJP: June 23, 1996[3]NA: September 29, 1996[1][2]EU/AU: March 1, 1997[4][5]Lifespan1996 (1996…

1st episode of the 4th season of ER AmbushER episodeEpisode no.Season 4Episode 1Directed byThomas SchlammeWritten byCarol FlintProduced by Paul Manning Christopher Chulack Featured musicMartin DavichCinematography byRichard ThorpeEditing byJim GrossProduction code456623Original air dateSeptember 25, 1997 (1997-09-25)Running time47 minutesEpisode chronology ← PreviousOne More for the Road Next →Something New ER (season 4)List of episodes Ambush is the premiere ep…

Mountain summit in Wales Carnedd GwenllianRocky summit of Carnedd Gwenllian looking South-southwest across the CarneddauHighest pointElevation925 m (3,035 ft)Prominence33 m (108 ft)Parent peakFoel-frasListingHewitt, Welsh 3000s, Nuttall, FurthNamingLanguage of nameWelshPronunciationWelsh: [ˈkarnɛð ɡwɛnˈɬiː.an]GeographyLocationSnowdonia, WalesOS gridSH687669 Listed summits of Carnedd Gwenllian Name Grid ref Height Status Bera Bach 807 m (2,648 ft…

Great Liao大遼1122–1123CapitalXijin FuReligion Tengrism, Buddhism, Taoism, Confucianism, Chinese folk religionGovernmentMonarchyEmperor • 1122 Yelü Chun• 1122–1123 Yelü Ding History • Yelü Chun enthroned as emperor 1122• Capture of Yelü Ding by Jin dynasty 1123 CurrencyChinese cash, Chinese coin, copper coins etc. Preceded by Succeeded by Liao dynasty Jin dynasty Today part ofChina The Northern Liao (simplified Chinese: 北辽; traditional Chin…

Not to be confused with Fred: The Movie. 2014 American filmFredDirected byJohn Fitzgerald KeitelProduced byJohn Fitzgerald KeitelStarringFred KargerProductioncompanyThinkFree TVRelease date April 4, 2014 (2014-04-04) (MonIFF) Running time62 minutesCountryUnited StatesLanguageEnglish Fred is a 2014 American documentary film that chronicles the 2012 presidential campaign of the first openly gay candidate in a major political party in American history, Fred Karger. Fred premiered…

1814 battle during the War of the Sixth Coalition This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Battle of Saint-Dizier – news · newspapers · books · scholar …

Edificio de los servicios públicos de Talca Monumento Histórico(Decreto N.º 2739, del 9 de septiembre de 2008) LocalizaciónPaís ChileUbicación TalcaCoordenadas 35°25′36″S 71°39′54″O / -35.426614, -71.665025Información generalUsos Oficinas públicasEstilo ModernismoDeclaración 9 de septiembre de 2008Inauguración 1930[editar datos en Wikidata] Fachada de Edificio El edificio de los servicios públicos de Talca corresponde a una construcción de estilo m…

2012 American filmFrayRelease poster for FrayDirected byGeoff RyanWritten byGeoff RyanProduced byJodi RedmondStarringBryan KaplanMarisa CostaWes HarrisCinematographyJarin BlaschkeEdited byGeoff RyanMusic byJacob LawsonDistributed byIndie RightsRelease dates April 13, 2012 (2012-04-13) (Arizona International Film Festival) April 18, 2014 (2014-04-18) CountryUnited StatesLanguageEnglish Fray is a 2012 independent film starring Bryan Kaplan and Marisa Costa. It was…

Kembali kehalaman sebelumnya