動的型付け

動的型付け(どうてきかたづけ、: Dynamic typing)とは、オブジェクト型安全性を、実行時に検証するというコンピュータプログラミング型システムの方法である。型の検査は実行時のプロセス上で行われて、ランタイムシステムの実行時型情報(RTTI)が照会されるなどして解析される。

動的な型チェックは、代入、束縛、関数適用、ダウンキャスト、ディスパッチ、バインディングといった所で行われる。なお、コンパイル時やインタプリタ開始時の最適化によってすでに型安全性が保証されている所は省略される。動的型付けの言語では、引数や返り値や変数宣言への型注釈が省略されやすくなる。

対義語は静的型付けであり、こちらでは値やオブジェクトの型安全性コンパイル時に検証する。型の検査はソースコードの解析によって行われる。

概要

動的型付けのルーツはLISPにさかのぼる。LISPは、同時期のFORTRANCOBOLとは一線を画した、計算モデルラムダ計算)を裏付けに持つ言語であった。しかし型付きラムダ計算ではなく、実行前に型チェックが行われることもなく、型エラーはその式が評価(実行)されるまでわからないという欠点、すなわち動的型付き言語特有の欠点を持つ初期の言語である。その後、LOGOを経て、動的な型という概念を明確にしたのがSmalltalkである[1]。そして、このような性質の言語を動的型付き言語(どうてきかたつきげんご、: dynamically-typed languages)という。

オブジェクト指向にもとづく Smalltalk では、すべての処理対象は何らかのクラスに属すため、型という概念そのものは存在する。しかし Smalltalk では、

  • すべてのクラスはルートクラスである Object に由来するので、最低限 Object としての振る舞いが保証される。
  • たとえ同一の機能名を持っていても、実際に起こる結果はクラスによって異なるかもしれない。
  • クラス(型)自体も一種のオブジェクトであり、必要ならクラスに関するメタプログラミングが行える。

などの特徴を持ち、型よりもむしろ「特定の名称のメソッドを受け付けるべき」「メソッドはその名前に見合った動作を行うべき」というプロトコル[2]的な立場による疎結合の信頼性を重視している。このプロトコル的な信頼性こそが動的型付けの要である。これを積極的に行うのがダック・タイピングである。

両者の違いは、静的は予防的な立場であり、動的は自浄的な立場といえるだろう。

通常、静的型付けはオペレーティングシステムシステムプログラムのような大規模で厳密性が要求される領域に適合するといわれている。その反面、最初の型定義を誤ると一部分の影響が全体に波及すること、また柔軟性に乏しくわずかな変換に手間のかかる経路を用意したり同じような機能を型別に実装しなければならないことなど、いわばお役所仕事的な煩雑さを伴うという弱点を持つ。この煩雑さは IDE によるリファクタリングの支援によって軽減され得る。なお近年[いつ?]の研究により、静的型付き言語も文脈から型を推論する型推論能力を持つなど、簡略化の方向へ向かってはいる。

一方、動的型付き言語ではそもそも対象に特定の構造を期待しないため、変更への対応は柔軟である。特に配列、辞書、集合といったコレクションの利便性が顕著で、そのため近年[いつ?]いわゆるスクリプト言語動的プログラミング言語は多くが動的型付けを採用している。動的型付けの難点である最適化の弱さは、コンピューターの能力が増すことで相対的に小さな問題になっており、スクリプト言語を中心に今後も動的型付けは発展するものと思われる[3]

静的型付けとの比較

静的型付けは、

  • 機能(関数)が形式に合った正しい型のデータのみを処理することを事前の検査により保証する
  • この保証があるため、高度な最適化が可能である

と主張される。この方向性に基づき、全ての機能と変数において処理する対象の型をプログラムの定義時点で決定し、型が異なるデータを受け付けない(あるいは上位互換の型に限定する)。MLなどでは型に従わない式は許されない。Javaなどでは明示的にキャストする必要があり、キャストは実行時に検査される。Cなどではキャストを正しく使うのはプログラマの責任であり、通常のコンパイラは特にチェックなどを入れず書かれた通りのコードを吐く。

これに対し、動的型付けでは、定義では型の限定を行わず、実行時に合致するデータが渡されると期待する、または合致するデータであるかを判定する。期待する型とは異なるデータが渡された場合、単にエラーとするものもあれば、型変換ないし強制(coerce、数値を文字列にしたりするような変換)したり、場合によっては委譲といったプロトコルに従うものもある。

例えば、Perl, Pythonで共に実行可能(文法エラーとはならない)な下記のコードにおいて、Perlでは20と表示される一方、Pythonでは実行時にTypeError例外が発生する。なおこの2種類を「強い動的型付け」「弱い動的型付け」と区別するのは間違いである(どちらも、プログラムが異常なまま走り続けることは無いので、強い型付けである)。

print('10'+10);

プログラムの最適化手法のうち、静的型付けでは容易だが動的型付けでは難しいものがあり、動的型付けが不利とされる理由のひとつになっている。

脚注

  1. ^ 関数型プログラミング言語から、もう一方の側である静的型付き言語には、MLHaskell へという発展があった。
  2. ^ インターフェイスとも言う。
  3. ^ ただし、徹底的な最適化がほどこされるのは、V8など特に投資が大きい一部の実行環境に限られる。

関連項目

Read other articles:

У Вікіпедії є статті про інші значення цього терміна: Старий і море (значення). Старий і мореангл. The Old Man and the Sea Обкладинка українського видання, 2017Жанр повістьФорма нарація[d]Тема мореАвтор Ернест ГемінгвейМова англійськаНаписано 1952Країна  СШАВидавництво Scribner Видав

Downtown neighbourhood in Whitehorse, Yukon, Canada Skyline of Downtown Whitehorse from the east side of the Yukon River. Downtown Whitehorse is a neighbourhood in Whitehorse, Yukon. The downtown area serves as Whitehorse's city centre and central business district. History Downtown Whitehorse originally encompassed the entirety of Whitehorse prior to the Second World War. After the war, the periphery was developed, with residents beginning to move into the Riverdale subdivision on the east b...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أغسطس 2019) لوان سانتانا (بالبرتغالية: Luan Santana)‏  لوان سانتانا عام 2017 معلومات شخصية اسم الولادة (بالبرتغالية: Luan Rafael Domingos Santana)‏[1][2]  الميلاد 13 مارس 1991 (العمر ...

American writer (1919–2010) J. D. SalingerSalinger in 1950BornJerome David Salinger(1919-01-01)January 1, 1919New York City, U.S.DiedJanuary 27, 2010(2010-01-27) (aged 91)Cornish, New Hampshire, U.S.OccupationNovelistshort-story writerEducationNew York UniversityUrsinus CollegeColumbia UniversityNotable worksThe Catcher in the Rye (1951)Nine Stories (1953)Franny and Zooey (1961)Raise High the Roof Beam, Carpenters and Seymour: An Introduction (1963)Spouse Sylvia Welter ​ R...

Laotisch (ພາສາລາວ) Gesprochen in Laos Laos, Thailand Thailand Sprecher 3,3 Millionen Muttersprachler; min. 800.000 Zweitsprachler[1] (ohne Isan) LinguistischeKlassifikation Tai-Kadai-Sprachen Kam-Tai-Sprachen Tai-Sprachen Südwestliche Tai-Sprachen Laotisch Offizieller Status Amtssprache in Laos Laos Anerkannte Minderheiten-/Regionalsprache in Vietnam Vietnam Sprachcodes ISO 639-1 lo ISO 639-2 lao ISO 639-3 lao[1] Die laotische Sprac...

El texto que sigue es una traducción defectuosa. Si quieres colaborar con Wikipedia, busca el artículo original y mejora esta traducción.Copia y pega el siguiente código en la página de discusión del autor de este artículo: {{subst:Aviso mal traducido|Pasaporte a Europa con Samantha Brown}} ~~~~ Pasaporte a Europa con Samantha Brown es un programa de televisión de Travel Channel. El programa sigue a la presentadora de televisión burbujeante y alegre Samantha Brown de Europa visitando...

Терджиман ترجمان Тип тижневик, щоденнаМова кримськотатарська, тюркі, російськаМісце публікації БахчисарайВидавець Ісмаїл Гаспринський, Зухра АкчурінаФормат інформаційний, просвітницький, 4 с. Засновано 1883Власник Ісмаїл ГаспринськийРедактор Ісмаїл Гаспринський,...

Bupati SragenLambang Kabupaten SragenPetahanadr.Hj. Kusdinar Untung Yuni Sukowatisejak 17 Februari 2016KediamanPendopo Bupati SragenMasa jabatan5 tahunDibentuk1861Pejabat pertamaK. R. T. SastropuroSitus websragenkab.go.id Berikut adalah Daftar Bupati Sragen dari masa ke masa. No Foto Nama Mulai Jabatan Akhir Jabatan Wakil Bupati Keterangan Ref. 1. - K. R. T. Sastropuro 1861 1871   2. K. R. T. Wirjodiprodjo 1871 1903   3. K. R. M. T. Panji Sumonegoro 1903 1933   4. - K. R. ...

18°01′00″N 63°02′00″W / 18.0167°N 63.0333°W / 18.0167; -63.0333 يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (فبراير 2016) موقع جزر أس أس أس في البحر الكاريبي، ومن أعلى لأسف�...

Tideford Cross Tideford Cross is a hamlet in Cornwall, England, United Kingdom. It is about one mile north of Tideford.[1] References ^ Ordnance Survey One-inch Map of Great Britain; Bodmin and Launceston, sheet 186. 1961. vte Ceremonial county of CornwallCornwall PortalUnitary authorities Cornwall Council Council of the Isles of Scilly Major settlements(cities in italics) Bodmin Bude Callington Camborne Camelford Falmouth Fowey Hayle Helston Hugh Town Launceston Liskeard Looe Lostwit...

Process by which a gene can code for multiple proteins Alternative splicing produces three protein isoforms. Protein A includes all of the exons, whereas Proteins B and C result from exon skipping. Alternative splicing, or alternative RNA splicing, or differential splicing, is an alternative splicing process during gene expression that allows a single gene to code for multiple proteins. In this process, particular exons of a gene may be included within or excluded from the final, processed me...

Logic-based number-placement puzzle This article is about the puzzle. For the disease, see Sodoku. A typical Sudoku puzzleThe solution to the puzzle above Sudoku (/suːˈdoʊkuː, -ˈdɒk-, sə-/; Japanese: 数独, romanized: sūdoku, lit. 'digit-single'; originally called Number Place)[1] is a logic-based,[2][3] combinatorial[4] number-placement puzzle. In classic Sudoku, the objective is to fill a 9 × 9 grid with digits so that e...

Canadian law professor (born 1977) Benjamin AlarieBorn1977 (age 45–46)Kitchener, Ontario, CanadaNationalityCanadianEducationStudied at Wilfrid Laurier University (B.A.), University of Toronto (M.A., J.D.), Yale Law School (LL.M.)Alma materWilfrid Laurier University, University of Toronto, Yale Law SchoolOccupation(s)Lawyer, legal scholar, entrepreneurEmployerUniversity of Toronto Benjamin Alarie (born 1977) is a Canadian jurist, law professor, and entrepreneur. He serves as Pr...

Show de Municipality in the State Aldama is a municipality of the northeastern Mexican state of Tamaulipas. According to the census of 2010, the municipality had an area of 3,672 square kilometres (1,418 sq mi) and a population of 29,470, including the town of Aldama with a population of 13,661.[1] History The region of Aldama prior to the arrival of the Spaniards in the early 16th century was the northern outpost of the Huastec culture, a maize growing culture remotely rela...

Book by Michael Medved Hollywood vs. America: Popular Culture and the War on Traditional Values First editionAuthorMichael MedvedCountryUnited StatesLanguageEnglishGenreSocial Trends, Popular Culture, cultural relativismPublisherHarperCollinsPublication dateOctober 1992Pages400 p. (hardback edition), 416 p. (paperback edition)ISBN006016882X (Hardback), ISBN 0060924357 (Paperback)Preceded byThe Hollywood Hall of Shame: The Most Expensive Flops in Movie History Followed bySa...

Gubernatorial elections were held in Massachusetts November 5, 1867 1867 Massachusetts gubernatorial election ← 1866 November 5, 1867 (1867-11-05) 1868 →   Nominee Alexander Bullock John Quincy Adams II Party Republican Democratic Popular vote 98,306 70,360 Percentage 58.24% 41.69% Governor before election Alexander Bullock Republican Elected Governor Alexander Bullock Republican Elections in Massachusetts General 1942 1944 1946 1948 1950 1952 19...

Clan Tipo de canal Televisión digital terrestreTelevisión por suscripciónProgramación InfantilPropietario RTVEOperado por TVEPaís España EspañaIdioma Español(incluye pista con audiodescripción en castellano)Inglés (disponible como audio secundario)Fundación 2005Inicio de transmisiones 12 de diciembre de 2005Personas clave Manuel FareloYago FandiñoFormato de imagen 1080i HDTV(reescalado a 16:9 576i para la señal en resolución estándar y a 16:9 480i/576i para la señal inter...

Álvaro Mutis Información personalNombre de nacimiento Álvaro Mutis Jaramillo Nacimiento 25 de agosto de 1923 Bogotá (Colombia) Fallecimiento 22 de septiembre de 2013 (90 años)Ciudad de México (México) Causa de muerte Insuficiencia respiratoria Nacionalidad ColombianaFamiliaPadres Carolina Jaramillo ÁngelSantiago Mutis DávilaCónyuge Mireya Durán Solano, María Luz Montané, Carmen Miracle FeliúHijos Santiago MutisInformación profesionalOcupación Escritor Género Poesía y novela ...

2017 Formula One racing car Mercedes AMG F1 W08 EQ Power+The F1 W08 EQ Power+, driven by Lewis Hamilton, during the 2017 Malaysian Grand Prix.CategoryFormula OneConstructorMercedesDesigner(s)Paddy Lowe (Technical Director) Aldo Costa (Engineering Director)Geoff Willis (Technology Director)Mark Ellis (Performance Director) John Owen (Chief Designer) Loïc Serra (Chief Vehicle Dynamicist) Russell Cooley (Chief Engineer)Mike Elliott (Head of Aerodynamics) Jarrod Murphy (Chief Aerodynamicist)Andy...

For the radio station that held the call sign KFGO-FM at 101.9 FM in Fargo, North Dakota from 1986 to 2002, see KRWK. 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 possibly contains original research. Please improve it by verifying the claims made and adding inline citations. Statements consisting only of original research should be removed. (October 2015) (Learn how and wh...