ArticleslgStudy

science

Gradual typing

Gradual typing is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Gradual typing rather than just read about it. In short: Gradual typing is a type system that allows for both static typing and dynamic typing but enforces types at runtime. Gradual typing allows software developers to choose either type paradigm as appropriate, from within a single language.

Key takeaways

  • Gradual typing belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Gradual typing to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Gradual typing from memory before moving on to harder problems.

Reference excerpt

Gradual typing is a type system that allows for both static typing and dynamic typing but enforces types at runtime. Gradual typing allows software developers to choose either type paradigm as appropriate, from within a single language. In many cases gradual typing is added to an existing dynamic language, creating a derived language allowing for, but not requiring, static typing to be used. In some cases, a language uses gradual typing from the start. However, there are performance and implementation complexity tradeoffs compared to dynamic or optional typing.

History The term was coined by Jeremy Siek, who developed gradual typing in 2006 with Walid Taha.

Implementation In gradual typing, a special type named dynamic is used to represent statically-unknown types. The notion of type equality is replaced by a new relation called consistency that relates the dynamic type to every other type. The consistency relation is reflexive and symmetric but not transitive. Prior attempts at integrating static and dynamic typing tried to make the dynamic type be both the top and bottom of the subtype hierarchy. However, because subtyping is transitive, that results in every type becoming related to every other type, and so subtyping would no longer rule out any static type errors. The addition of a second phase of plausibility checking to the type system did not completely solve this problem. Gradual typing can easily be integrated into the type system of an object-oriented language that already uses the subsumption rule to allow implicit upcasts with respect to subtyping. The main idea is that consistency and subtyping are orthogonal ideas that compose nicely. To add subtyping to a gradually-typed language, simply add the subsumption rule and add a subtyping rule that makes the dynamic type a subtype of itself, because subtyping is supposed to be reflexive. (But do not make the top of the subtyping order dynamic!)

Comparison With Optional Types Gradual and optional typing are similar in that variables and expressions may be given types and the correctness of the typing is checked at compile time (which is static typing). However, in a gradual type system, runtime checks are inserted at the boundaries of typed and untyped code. In an optional type system, all types are erased at compile time and untyped values can propagate through code that had type annotations.

In a gradually typed language, an exception would be raised anytime a non-integer value is supplied for credit and stack traces would stop at invalid calls (new Account("2")). In an optionally typed language, an exception would only be raised when the language is forced to perform operations that would be incompatible with its type: credit can be set to "1" (a string) but this would only throw an error when performing math on it (e.x. when spendCredit attempts to subtract the integer 1). compare functions as normal, illustrating how a program running in production could create and manipulate invalid Accounts without triggering an error. This could result in data corruption if the invalid instances are saved to a datastore.

Getting similar results in an optionally typed language requires a programmer to manually perform type checking by inserting guards:Note however, that stack traces won't trace to the offending call but the setter. If the programmer forgets to pass externally provided values through the setter, it's still possible that an invalid instance could be created and saved to disk but discovered during a later execution. This makes data corruption harder to prevent and impedes tracking down offending code paths.

Implementations Examples of gradually typed languages derived from existing dynamically typed languages include Closure Compiler, Hack (for PHP), PHP (since 7.0), Typed Racket (for Racket), Typed Clojure (for Clojure), or cperl (a typed Perl 5). ActionScript was a gradually typed language that interoperated with ECMAScript, though it originally arose separately as a sibling, both influenced by Apple's HyperTalk. A system for the J programming language has been developed, adding coercion, error propagation and filtering to the normal validation properties of the type system as well as applying type functions outside of function definitions, thereby the increasing flexibility of type definitions. Conversely, C# started as a statically typed language, but as of version 4.0 is gradually typed, allowing variables to be explicitly marked as dynamic by using the dynamic type. Raku (formerly Perl6) has had gradual typing implemented from the start. Type checks occur at all locations where values are assigned or bound. An "untyped" variable or parameter is typed as Any, which will match (almost) all values. The compiler flags type-checking conflicts at compile time if it can determine at compile time that they will never succeed. Objective-C has gradual typing for object pointers with respect to method calls. Static typing is used when a variable is typed as pointer to a certain class of object: when a method call is made to the variable, the compiler statically checks that the class is declared to support such a method, or it generates a warning or error. However, if a variable of the type id is used, the compiler will allow any method to be called on it. The JS++ programming language, released in 2011, is a superset of JavaScript (dynamically typed) with a gradual type system that is sound for ECMAScript and DOM API corner cases. GDScript, the Godot game engine's primary scripting language, started out dynamically typed and introduced gradual typing with version 3.1 of the engine, allowing users to type variables, function parameters, arrays and dictionaries through type hints. Additionally, when assigning a value to a variable using the := notation, Godot will attempt to infer the type of the variable at build time.

References

Further reading Siek, Jeremy G.; Vitousek, Michael M.; Cimini, Matteo; Boyland, John Tang (2015). Ball, Thomas; Bodik, Rastislav; Krishnamurthi, Shriram; Lerner, Benjamin S.; Morrisett, Greg (eds.). Refined Criteria for Gradual Typing. Leibniz International Proceedings in Informatics. Vol. 32. Dagstuhl, Germany: Schloss Dagstuhl–Leibniz-Zentrum fuer Informatik. pp. 274–293. doi:10.4230/lipics.snapl.2015.274. ISBN 9783939897804. S2CID 15383644.

Worked examples

Example 1 — a first encounter with Gradual typing

Start with the simplest possible case. Write down what Gradual typing claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Gradual typing before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Gradual typing ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Gradual typing

In research
Gradual typing appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Gradual typing in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Gradual typing is common in secondary-school and first-year university syllabi. It links to neighbouring topics Type systems, so understanding it makes those chapters shorter.
In everyday life
Look for Gradual typing outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Gradual typing” →

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Gradual typing in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Gradual typing means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Gradual typing out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Gradual typing in simple terms?

Gradual typing is a type system that allows for both static typing and dynamic typing but enforces types at runtime. Gradual typing allows software developers to choose either type paradigm as appropriate, from within a single language.

Why does Gradual typing matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Gradual typing?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Gradual typing.

Tags

  • Type systems

Keep exploring