A programming language specifies how programs are written and what their execution means. Its type system describes which operations may be combined; an abstract syntax tree records the structure on which these rules act. The examples under type system use a small teaching language with integers, Boolean values and function types.
// Target: computer-science.bigb
WebAssembly is a portable, low-level code format with precisely specified execution and validation rules. Programs are organized into WebAssembly modules, often produced by compilation from another programming language. Its type system and stack machine semantics make operations explicit. Although designed with web applications in mind, the core format does not require a web browser.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Introduction; design goals, execution and embedding
Here is a small WebAssembly text format module exporting addition:
(module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)). The two local.get instructions put the arguments on the operand stack; i32.add consumes them and produces one 32-bit result. The function maps inputs 3 and 4 to 7.[ref]WebAssembly Core Specification by the W3C WebAssembly Community Group. Text format, Modules and Functions; integer instruction types
Integer addition wraps modulo . For example, adding one to the bit pattern representing produces zero, rather than an arbitrarily large integer. This is a rule of the machine format, not a numerical approximation.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Numerics, iadd
A WebAssembly module obtains external facilities through its host and imports. WebAssembly linear memory is a controlled memory abstraction, not unrestricted access to every host address. Validation and runtime checks provide specified boundaries, but they do not make every allowed computation harmless: an imported operation has the authority that the host gives it.
A WebAssembly store is the abstract runtime state containing allocated entities such as function, memory, table and global instances. A WebAssembly module instance refers to these entities through WebAssembly abstract addresses. A store memory address selects a memory instance; it is distinct from a byte offset within WebAssembly linear memory.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Runtime Structure: Store, Addresses and Module Instances
For an original toy model, let the store contain two memory instances at abstract addresses 0 and 1. Module instances A and B both use local memory index 0, but A maps it to address 0 and B maps it to address 1. A third instance C imports the first memory and maps its own local index 0 to address 0.
Initially, let byte offset 0 in both memories contain zero. Writing 17 through A changes the first memory. Reading offset 0 through B gives zero, while reading it through C gives 17. There are three distinct coordinates: the module-local index, the store address selecting a memory and the offset selecting a byte inside it. Equal local index numbers do not establish sharing.
These invented addresses illustrate the semantics; they are not exposed machine addresses measured from an engine. The WebAssembly store also is not one linear memory or a persistent file store. The abstract model records allocations, while implementations may reclaim unreachable entities when doing so is not semantically observable.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Runtime Structure: Store note on garbage collection/reference counting; Addresses
A WebAssembly abstract address identifies an allocated runtime entity in the appropriate component of the WebAssembly store. Its kind distinguishes a function, memory, table or other entity. It differs from a module-local index and from an offset into WebAssembly linear memory.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Runtime Structure: Addresses and Module Instances
For an original lookup example, let the store's memory at address 0 contain bytes
10,11,12, and its memory at address 1 contain 20,21,22. A WebAssembly module instance maps local memory indices 0,1 to store addresses 1,0. Accessing its local memory index 0 at byte offset 2 therefore gives 22; local memory index 1 at the same offset gives 12.The numerical labels need their context. A memory address 1 and a function address 1 select different store components. Byte offset 1 instead selects a location within an already selected memory. Thus writing down the integer 1 alone does not specify which of these references is intended.
The example uses invented store indices, not host-machine pointers observed from an engine. The specification uses abstract addresses to describe how runtime references resolve. WebAssembly module declarations supply local indices, instantiation establishes their runtime mappings, and memory instructions apply offsets within the selected object.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Runtime Structure: Store, Addresses and Module Instances
A WebAssembly module instance is the runtime realization of a WebAssembly module. It collects references to the functions, memories and other entities that the WebAssembly module imports, defines or exports. The WebAssembly store contains the allocated runtime objects; a module's local indices are resolved through the corresponding WebAssembly module instance.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Runtime Structure, Store and Module Instances
For example,
(module (memory (export "memory") 1)) declares and exports one page of WebAssembly linear memory. Instantiate this WebAssembly module twice. Each instantiation allocates its own declared memory, so writing17 into byte0 through the first WebAssembly module instance leaves byte0 in the second at zero. Code can be reused while mutable state remains distinct.[ref]WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Modules, Memory Allocation and Instantiation
The import case supplies a useful counterexample. If a WebAssembly module imports memory and two instantiations receive the same memory object, writes through one are visible through the other. The WebAssembly module instances are distinct but that resource is shared. Instantiation therefore links imported entities as well as allocating local definitions; it also initializes active segments and invokes the start function when one is present.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Modules, Instantiation; Runtime Structure, Module Instances
WebAssembly linear memory is an indexed sequence of bytes accessed by WebAssembly memory instructions. Its runtime representation records its type and current byte sequence. The length is a multiple of the WebAssembly page size, bytes, or . Declared limits give an initial minimum and optionally a maximum size in pages.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Runtime Structure, Memory Instances; Syntax, Types, Memory Types
A load must fit its entire access into the current WebAssembly linear memory. For an instruction offset of zero, a four-byte
i32.load in a one-page memory succeeds at address : its last accessed byte has address . At address , it would need a byte at address and therefore traps. In general, effective address and width must satisfy , where is the current length; the check includes the instruction's immediate offset.[ref]WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Memory Instructions, numeric load algorithm, steps 3–6
This boundary example also distinguishes alignment from bounds. Ordinary unaligned loads are permitted; their alignment annotation is an optimization hint. A successful bounds check establishes that the accessed bytes lie inside this memory. It does not establish that the program selected its intended object.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Memory Instructions, alignment note
The WebAssembly text format is the readable textual encoding of WebAssembly modules. Parenthesized declarations describe the same structured program that can be encoded in binary. Symbolic identifiers such as
$add help readers refer to definitions; numeric indices determine references in the underlying module.[ref]WebAssembly Core Specification by the W3C WebAssembly Community Group. Text format, Modules, Functions and Exports; Text format, Values, Identifiers
For example,
(module (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)) declares and exports a function accepting two 32-bit integers. The local.get instructions push its arguments onto the operand stack; i32.add consumes them and produces the result. Inputs 3 and 4 give 7. The folded instruction (i32.add (local.get 0) (local.get 1)) is an alternative notation for the same instruction sequence.[ref]WebAssembly Core Specification by the W3C WebAssembly Community Group. Text format, Instructions, Folded Instructions; Numeric Instructions, iadd
The parentheses of a folded instruction make operand grouping visible, but do not introduce a different arithmetic operation. Decoding either spelling yields the same instruction structure. Textual readability and runtime behavior are separate: indentation can help a human follow the WebAssembly module, while the declared types and instruction order govern execution.
A WebAssembly module is the unit of deployment, loading and compilation in WebAssembly. It collects declarations such as functions, types and memories, can request imports, and can expose exports. Optional initialization includes data segments and a start function. A WebAssembly module is represented in a binary encoding or the readable WebAssembly text format.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Syntax, Modules, opening definition; Text format, Modules
Definitions use zero-based indices, with a separate index space for each kind of definition. Imported functions precede locally defined functions in the function index space. For example, with one imported function and two local functions, their function indices are respectively 0, 1 and 2; memory index 0 belongs to a different space. This explains why inserting a function import can change a numeric call target.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Syntax, Modules, Indices
A WebAssembly module instance is the runtime realization of these declarations, with references to the allocated or imported objects. Keeping a WebAssembly module distinct from a WebAssembly module instance separates a code description from the state used while executing it. Imported state can be shared; the mere use of the same module does not specify all its runtime resources.[ref]
WebAssembly Core Specification by the W3C WebAssembly Community Group. Execution, Runtime Structure, Module Instances
Pascal is a structured programming language designed by Niklaus Wirth for expressing algorithms with explicit data types, procedures and organized control statements. Its arrays and records support concrete data organization, while nested procedures permit local decomposition of a program.
For example, a procedure summing an array can declare an integer loop index and an accumulator, initialize the accumulator to zero, and use a
for loop to add each entry. Stating the supported integer range remains necessary: a clear source-level sum can still overflow bounded arithmetic. Niklaus Wirth's account dates the Pascal project to1968–1972 and records an operational first compiler in1970, followed by use in introductory teaching.[ref]Summary of projects 1962-1999 by Niklaus Wirth. Pascal,1968–1972
Logo is a programming language with procedures, lists and interactive evaluation, often used to make algorithmic ideas visible through turtle graphics. The turtle has a position and heading; motion commands can draw a line while changing that state. For example,
repeat 4 [forward 100 right 90] draws a square and returns to the initial heading. Each turn is an exterior angle, so a regular -gon uses turns of degrees.[ref]Berkeley Logo 6.2 User Manual by Brian Harvey. Graphics and Control Structures, FORWARD, RIGHT and REPEAT
A named procedure can package this instruction pattern and accept a side length as a parameter. Repeated calls and recursive procedures then produce more elaborate drawings without storing every line explicitly. The language also manipulates words and lists; turtle drawing is a useful experimental interface for studying programs, rather than the entire language.
Turtle graphics draws through commands interpreted relative to a moving cursor's position and heading. A forward command moves along the current heading, a turn changes it, and pen state determines whether motion leaves a mark. The picture is the trace of a sequence of state changes, making geometric reasoning executable.[ref]
Berkeley Logo 6.2 User Manual by Brian Harvey. Graphics, FORWARD, RIGHT, PENUP and PENDOWN
In Logo,
repeat 4 [forward 100 right 90] draws a square and returns to the original heading and position. For a regular -sided polygon, each exterior turn is degrees, so the total turning is one full revolution. The same procedure works from a different initial position or heading, illustrating how local commands avoid specifying every absolute coordinate.Programming abstraction exposes a useful interface while suppressing details that clients need not depend on. A procedure abstracts a computation, an abstract data type abstracts a representation and its operations, and a software module organizes a boundary between cooperating components. The contract must state the behavior on which callers may rely.
For example, a stack interface can offer push, pop and an empty test. An array implementation and a linked-list implementation can satisfy that same interface, although their allocation and cost behavior differ. A caller that inspects private array indices has crossed the abstraction boundary. A representation invariant and operation specifications explain why the implementation realizes the interface. Abstraction therefore supports local reasoning and replacement, while resource guarantees still need to be part of the contract when clients depend on them.
ALGOL 60 is a block-structured programming language specified through a formal report, with nested declarations, procedures, typed variables and structured statements for numerical algorithms. An identifier's meaning depends on its enclosing blocks, making lexical scope explicit. The revised report also uses a precise grammar to distinguish syntactic structure from the typography of a particular printed program.[ref]
Revised Report on the Algorithmic Language ALGOL 60 edited by Peter Naur. blocks, declarations and procedure statements
Its parameter mechanisms include call-by-value and call-by-name. The latter behaves through systematic replacement, with renaming to avoid accidental identifier capture, rather than simply copying one already evaluated value. A procedure that refers to a name parameter more than once can therefore evaluate its actual expression more than once. This matters when the expression depends on changing variables or has effects; the two calling conventions are not interchangeable.
Call-by-name passes a procedure argument so that each use of the formal parameter refers to the actual expression in its calling environment. In ALGOL 60, the report explains this through replacement with renaming to avoid accidental capture of identifiers. An expression can consequently be evaluated more than once.[ref]
Revised Report on the Algorithmic Language ALGOL 60 edited by Peter Naur. §4.7.3.2, Name replacement
Suppose the actual argument is
a[i]. The procedure reads its name parameter, changes i, and reads the parameter again. With call-by-name, the second access can select a different array entry. With call-by-value, both accesses use the value obtained before entering the procedure. This is also different from saving the original entry's address. Call-by-name does not imply lazy evaluation with memoization: repeated evaluation can repeat both work and side effects.Modula-2 is a systems programming language designed by Niklaus Wirth, combining structured programming with explicit software modules and facilities for low-level system construction. A definition module declares an exported interface; an implementation module supplies its implementation and private details. Clients import the declared names instead of depending on every declaration in the implementation.
For example, a stack module can export a stack type and push/pop procedures while keeping the array or linked representation private. This permits separate compilation against an interface and replacement of the implementation when its contract is preserved. Wirth's project account places Modula-2 in the Lilith workstation effort and records completion of its first compiler at ETH in1979.[ref]
Summary of projects 1962-1999 by Niklaus Wirth. Modula-2 and Lilith sections
Low-level facilities make hardware-oriented programs expressible, but also require care about the assumptions connecting language operations to devices and machine representations.An implementation module supplies the executable procedures and private declarations behind a Modula-2 module interface. Its associated definition module determines which declarations clients may import. This separation lets clients depend on an interface while the implementation selects a representation.
For example, a counter module can export a procedure
Next while storing a private running count. Its implementation module defines how Next updates and returns that count; clients need not know the private variable's name. Replacing the storage mechanism is possible when the exported behavior remains compatible. The GNU Modula-2 manual illustrates separate definition and implementation source files, then compiles implementation modules before linking them into a software library.[ref]Building a shared library in the GNU Modula-2 documentation. §2.14, a.def/a.mod and compilation/linking example
A definition module declares the exported interface of a Modula-2 module. It tells clients which names and data types they can use, while the implementation module supplies procedure bodies and private details. The boundary supports separate compilation and programming abstraction.
For example, a stack interface can declare an abstract stack type and push/pop operations without exposing whether storage uses an array or a linked list. Clients should preserve the declared contract rather than inspecting hidden representation. GNU Modula-2 conventionally stores a definition module in a
.def file and parses it when compiling importing modules; it does not compile the definition module separately as executable code.[ref]Compiler options in the GNU Modula-2 documentation. §2.2, .def and .mod source-file handling
Prolog expresses programs through facts and rules and answers queries by solving goals. A rule such as
ancestor(X,Y) :- parent(X,Y). provides one way to establish a relationship. A recursive rule can search through intermediate parents. Unification matches a goal with a rule head and propagates bindings; backtracking explores alternative matches when a branch fails or another answer is requested.[ref]Getting started quickly in the SWI-Prolog manual. §2.1, rules and queries
The logical core is associated with Horn clauses and SLD resolution, but clause order and goal order also determine a conventional Prolog program's search behavior. A logically valid recursive specification can loop before reaching an available answer. Predicates with input/output effects and control operations add further operational behavior. Arithmetic evaluation is also distinct from term matching:
X = 1+2 builds a term, whereas X is 1+2 evaluates arithmetic in the usual Prolog interface.SLD resolution is a goal-directed inference rule for definite first-order Horn clauses. It selects an atom from the current goal, matches it with a suitably renamed clause head using a most general unifier, and replaces it by that clause's body, applying the same first-order substitution throughout the goal. Reaching the empty goal supplies a successful derivation.[ref]
For example, the rule
ancestor(X,Y) :- parent(X,Y) reduces the query ancestor(ada,Y) to parent(ada,Y). Matching the fact parent(ada,ben) then gives Y=ben. Alternative matching clauses create a search tree. Prolog normally selects the leftmost goal and searches clauses in order with backtracking; a recursive branch can therefore run indefinitely before another branch's valid answer is reached. The logical inference rule and the strategy traversing its alternatives are separate choices.A conversion inserted by the language's typing rules rather than an explicit conversion call in source code. Its availability depends on scope and the conversion rules; converting a method receiver and converting an argument are distinct uses. In Scala, an imported implicit conversion can supply a rational-number receiver for an integer expression lacking an applicable multiplication overload.
A language-defined conversion from a numeric type to another admitted numeric type, such as Scala's conversion of an
Int argument to Double. It can make an overloaded method applicable even when the argument's static type differs from the parameter type. It does not imply a subtyping relationship between every pair of numeric types or exact representation of every source value; sufficiently large integers can lose precision in a floating-point target. [ref]Scala 2.11 expressions specification. Numeric Widening
Oberon is a programming language designed by Niklaus Wirth, evolving from Modula-2 with a deliberately small collection of constructs. Its modules organize declarations and imports; record type extension relates new record types to existing ones. An extending record retains its base fields and can add more, supporting controlled specialization. The language and the Oberon operating-system project are distinct objects. Different revisions have different rules, so the cited language report matters when discussing exact syntax or type compatibility.[ref]
https://people.inf.ethz.ch/wirth/Oberon/Oberon07.Report.pdf. Wirth, The Programming Language Oberon, introduction and §§6,11
A call whose result is returned directly, with no further computation waiting in its caller. Its caller's activation record can therefore be replaced rather than retained. A recursive tail call gives tail recursion; an explicit loop updating the current arguments performs the same control transfer without requiring compiler optimization.
Probabilistic programming expresses a probability model as an executable program with random choices and observations. Executing the generative part induces a probability distribution; observations then restrict or weight executions, and inference computes the resulting conditional distribution. Program syntax and inference algorithm are separate choices: the same model can be evaluated by rejection sampling, importance sampling or Markov chain Monte Carlo.
A stochastic computation graph is a directed acyclic graph combining deterministic transformations, random choices and costs. The changing probabilities of random choices contribute score-function gradient estimators, while differentiable deterministic paths contribute pathwise gradients. This accounts for both sources of a parameter's effect on an expected cost.[ref]
A probabilistic program maps elementary random choices to outputs and observation weights. Its mathematical meaning can be specified by the pushforward measure on outputs, normalized after conditioning when the observation has finite positive mass. Different random-choice spaces can implement the same output law.
Let a model have parameter prior density , observation probability and conditional binary-query probability after observation. Draw and an independent uniform random variable . Accept exactly when , then output whether . At fixed , the accepted true and false intervals have lengths and . Integrating against and dividing by the positive evidence proves equality of the joint posterior law of parameters and answer. This can replace many latent choices by one auxiliary coordinate. It preserves that joint law, not unreported latent traces. More generally the bounded factor must be a probability or first be divided by a valid common rejection envelope.
Selecting a branch and binding components according to a value's constructor structure. In Haskell, matching a constructor can demand the outer constructor without demanding every field; a failed or undefined match has distinct consequences from an irrefutable pattern.
A pattern that does not force its matched value merely to establish the match. A Haskell pattern written with
~ can defer evaluation of a recursive pair until one component is demanded. This can preserve productivity in definitions involving lazy evaluation. It does not make every later use of the components terminate.A systems programming language supporting explicit memory access, arrays, and implementation-dependent integer widths. Signed integer overflow is not generally specified as modular arithmetic; correctness arguments must state the relevant range assumptions.
Volatile-qualified objects in C are objects whose accesses must follow the implementation's observable-access rules even when the optimizer cannot see an ordinary program dependency. They are commonly used for device registers and state changed by an interrupt handler, under the target compiler's embedded execution model.
volatile does not by itself provide atomic multiword access, mutual exclusion or inter-thread synchronization. Protecting a shared snapshot still requires a suitable critical section or another synchronization protocol.[ref]For a -bit unsigned integer type without padding, C programming language arithmetic on that type reduces results modulo . In particular, subtracting two
uint32_t timestamps gives their modular difference when that subtraction is evaluated in the 32-bit unsigned type. Integer promotions must be checked for narrower types or unusual implementations. Signed integer overflow has different rules and must not be treated as the same operation.[ref]A programming language expressing machine instructions through symbolic operation names, processor registers, labels and data directives. A concrete program must respect its instruction set's operand restrictions and the platform's calling convention.
A program that translates assembly language into machine code. A pseudo-instruction can expand into several instructions, for example to construct a constant that cannot fit one immediate operand.
An assembler convenience that expands into one or more actual machine instructions. Its expansion matters when counting instructions, reasoning about temporary registers, or filling a branch delay slot.
The agreement between a caller and a subroutine on argument and result placement, processor register preservation, and call stack organization. Callee-saved registers retain their incoming values across a call; caller-saved registers must be saved by the caller if their values are still needed afterwards.
The result a called procedure supplies to its caller on returning. A calling convention specifies the processor register or memory location carrying it, separately from the return address, which identifies where execution resumes. In the elementary MIPS architecture convention, an integer result is placed in
$v0, while $ra carries the return address.The saved instruction address at which execution resumes after a function returns. A recursive call must preserve the current return address before another call overwrites the link register.
The 32-bit calling convention for the ARM architecture family. Its base variant passes initial arguments in
r0–r3, returns a word in r0, preserves r4–r8, r10, r11, and sp, and requires eight-byte stack pointer alignment at public calls.[ref]A processor register that a subroutine may overwrite. A caller retaining a live value in such a processor register must preserve it elsewhere before calling. Argument and result processor registers commonly have this role.
A processor register whose incoming value a called subroutine must restore before returning if it modifies it. This lets a caller retain live values across calls, but the caller must in turn preserve its own caller's values when using these processor registers.
A type representing a finite sequence of characters or other specified text units. Its indexing and encoding conventions depend on the language. Immutable strings can be shared safely by a saved snapshot because later replacement of a variable does not mutate the saved string's contents.
A programming language supporting object-oriented programming and functional programming. Its traits support reusable mixin behavior, while type variance controls how parameterized types participate in subtyping. The Scala 2 and Scala 3 language versions differ in some syntax and typing details; examples should state the version relevant to a particular claim. Official documentation: docs.scala-lang.org
Scala Swing provides Scala wrappers for Java Swing graphical user interfaces. Its notification mechanism implements an observer pattern: a publisher emits software events, and a reactor subscribes with
listenTo(publisher). Adding a handler to reactions supplies a partial function that matches the software events the reactor handles. Subscription and handling are distinct: one determines which publisher is heard, and the other determines what to do with a matching notification.[ref]For example, a button publishes a button-click notification, and a subscribed display component handles it by updating a label. Another publisher's notifications need a subscription of their own. Calling
deafTo(publisher) ends the subscription to that publisher without requiring removal of every handler.[ref]A functional programming language with parametric polymorphism and lazy evaluation. The code examples here use the Haskell 2010 Language Report specification.
The function
zip :: [a] -> [b] -> [(a,b)] pairs corresponding list positions, stopping when either input ends. Pairing a finite list with [0..] attaches its zero-based indices without constructing an infinite result. With the unbounded Integer index type this avoids index overflow for arbitrarily long finite inputs.The higher-order function
takeWhile :: (a -> Bool) -> [a] -> [a] retains the longest initial segment whose elements all satisfy its predicate. It stops at the first failure and does not resume later. Thus it differs from a list filter, which tests later elements as well.The higher-order function
iterate :: (a -> a) -> a -> [a], satisfying iterate f x = x : iterate f (f x). Its result begins with the initial value and continues with successive applications. Lazy evaluation permits finite prefixes of this infinite list to be observed whenever the necessary applications terminate.The higher-order function with type
(a -> [b]) -> [a] -> [b] and value concat (map f xs). It replaces each input element by a list and concatenates those lists in input order. A direct definition is concatMap f = foldr (\x rest -> f x ++ rest) []. This formulation processes an input element's produced list once; it need not repeatedly append an already accumulated output prefix.A partially applied infix operator:
(a op) means \x -> a op x, and (op b) means \x -> x op b, subject to Haskell's syntax rules. In particular, (f .) maps a function g to the function composition f . g. Composing such a section with a curried binary function composes at two argument levels: ((f .) . g) x y = f (g x y) on total inputs.[ref]Haskell 2010 Language Report. §3.5, Sections
The automatically available standard module of Haskell, supplying basic types, classes and operations such as list folds, arithmetic and list comprehension support. A program can explicitly hide an imported name when providing an alternative definition. The reference definitions specify behavior, rather than requiring a particular implementation strategy.[ref]
Haskell 2010 Language Report. Chapter 9, introductory paragraphs and module Prelude exports
MATLAB is a numerical programming language and computing environment organized around arrays and matrix operations. A matrix multiplication expresses a mathematical linear-algebra operation directly, while elementwise multiplication applies independently to corresponding entries; confusing the two changes the computation. The environment includes visualization and numerical libraries, with additional capabilities supplied through toolboxes. Most ordinary numerical calculations use finite-precision arithmetic, so algebraically equivalent expressions can differ through rounding. The language and environment are developed by MathWorks.[ref]
R is a programming language and environment for statistics, data analysis and graphics. For matrix algorithms,
drop = FALSE preserves dimensions when extracting submatrices. To choose an element uniformly from a possibly singleton numeric vector indices, use indices[sample.int(length(indices), 1L)]: sample(indices, 1L) has a special interpretation when its first argument is a single positive number. Official documentation: Extraction and the drop argument and Sampling, including the singleton numeric argument rule.A list comprehension constructs a list by applying an expression to elements selected through generators and optional predicates. In Python,
[x*x for x in range(5) if x % 2 == 0] gives [0, 4, 16]. The generator sets the traversal, the predicate filters values and the expression transforms those retained. Nested generators preserve an order, so changing them can change output order and termination for infinite inputs in lazy languages. A Python list comprehension constructs the whole result eagerly; a generator expression instead produces values on demand.[ref]For a binary operation , its Cartesian lifting sends lists to the list comprehension , with the right generator varying fastest. On finite lists this preserves associativity but need not preserve commutativity or idempotence, because list order and repeated entries matter.
A programming language whose program is an ordered list of positive rational numbers. Starting with a positive integer, multiply by the first listed fraction that produces an integer, then repeat; halt if none applies. Encoding registers as prime exponents relates this operation to a register machine.
A word selecting specified binary positions under a bitwise operation. To extract a stored bit at position , logically shift by and combine with the mask
1. Grouping thirty-two cells into one Java integer permits a compact representation of a Conway Game of Life board.// Destination: computer-science.bigb
A submask of a bit mask is a bit mask whose set bits are all set in , equivalently . It represents a subset of the positions selected by . If has set bits, it has exactly submasks, including zero.
To enumerate them in descending order, start at , output , stop if , and otherwise replace it by . Subtracting one clears the lowest set bit and fills lower positions; masking removes positions unavailable in . For , the sequence is . Testing for zero before the next update is essential: under the common integer conventions, updating zero produces again and repeats the cycle.[ref]
Enumerating submasks of a bitmask in the CP-Algorithms documentation. Enumerating all submasks of a given mask
The number of outputs is exponential in the number of selected positions, even though each fixed-word update is inexpensive.A submask of a bit mask has no set bits outside . Start with and repeatedly replace a positive byProcess each positive before this update and stop when it becomes zero. To include the empty submask, process zero once and stop before updating it; otherwise the update can return to .
Subtracting one clears the lowest set bit and sets the lower positions. The bitwise AND with removes forbidden positions, producing the largest permitted submask strictly below the previous one. This proves decreasing order, no duplicates and no skipped submask.
For , the order is . A bit mask with set bits has submasks, because each allowed position is independently selected or omitted. Enumeration therefore takes updates under constant-cost bitwise operations; has only the empty submask.
A bitboard represents occupied positions on a finite board by the bits of an integer. Bitwise operations combine occupancy masks and test whether pieces overlap.
Bitwise OR combines binary representations position by position: an output bit is one exactly when at least one input bit is one. On bit masks representing sets, it computes their union.
A fixed-width left shift discards high bits and inserts low zeros. A logical right shift inserts high zeros; an arithmetic right shift propagates the sign bit. In Java,
<<, >>> and >> distinguish these operations. Left shift by is multiplication by modulo the word modulus.// Destination: computer-science.bigb
A bit rotation cyclically moves the bits of a fixed-width machine word: positions discarded at one end reappear at the other. A logical shift instead fills vacated positions with zero and discards outgoing bits. Consequently they have different wiring at the edge of a barrel shifter.
An arithmetic right shift propagates the sign bit into the vacated high positions. For a signed two's complement integer, its result is division by rounded down. This differs from C integer division on negative nonmultiples of , because that quotient truncates towards zero. Shifting an -bit word arithmetically by produces zero for a nonnegative value and the all-one word, representing , for a negative value.
A logical right shift moves bits toward less significant positions, discards those shifted out, and fills the high positions with zero. On the unsigned interpretation of a machine word, it computes the quotient in integer division by . Indeed, splitting the binary representation after its lowest bits gives with ; the retained upper bits represent . A fixed-width left bit shift by followed by a logical right shift by extracts precisely the low bits, giving the remainder.
A bit shift toward more significant positions, filling low positions with zeros. On an unbounded nonnegative integer, shifting left by places multiplies it by ; fixed-width representations may discard overflowing high bits.
For a fixed word width , signed integers have the same bit patterns as residues modulo . The leading bit has negative positional weight in the signed interpretation. Reading the same bits as unsigned gives for a negative signed integer .
// Destination: computer-science.bigb
To widen an -bit two's complement integer to bits, preserve the original low bits and fill the new high positions with the old sign bit . The change in signed positional weights is , so the represented signed value is unchanged. Zero extension instead preserves the unsigned interpretation, and changes the signed value of negative inputs.
Base-sixteen representation, with digit values zero through fifteen conventionally written
0 through 9 and a through f. A group of four binary digits selects one hexadecimal digit.// Destination: computer-science.bigb
An abstract syntax tree is a rooted tree recording the meaningful syntactic pieces of a program and how they fit together. A program identifier such as
x, a literal value such as 2, and a node representing addition have different roles. Their arrangement answers structural questions: which program expression supplies an operand, which name is a variable assignment target, and which construct encloses another. This makes an abstract syntax tree useful to a compiler, an interpreter, and the type system that checks a program.The word "abstract" describes what is omitted. Lexical analysis first recognizes lexical tokens, such as
x, =, 2, +, 3, *, 4. A concrete parse tree can retain grammar derivation structure, including punctuation and intermediate context-free grammar categories such as expression, term and factor. An abstract syntax tree usually keeps the operation and its operands without all those grammar scaffolds. Parentheses can determine its shape without surviving as separate nodes. A parser may construct the abstract syntax tree directly; it need not first allocate a concrete parse tree.An abstract syntax tree records programming language syntax, but does not by itself supply all programming language semantics. In
a+b, the names do not reveal their current values, and + might perform addition of integers or concatenate strings. The programming language rules, name bindings, and operand types determine the meaning. In Python, successfully calling ast.parse also does not guarantee that later compilation will accept the result: parsing return 42 succeeds, but compiling that statement outside a function fails. [ref]ast — Abstract syntax trees, Python 3.14 documentation. ast.parse: parsing performs no scoping checks; the return 42 example
An abstract syntax tree is not machine code. Its nodes describe language constructs. A compiler can check and transform this structure before translating it into executable instructions; an interpreter can evaluate an appropriate tree directly. The little evaluator below demonstrates this distinction without pretending to implement an entire programming language.
The syntax tree of a logical formula records its recursive construction. A propositional variable is a leaf, negation has one child, and binary implication has an ordered pair of children. A subformula occurrence corresponds to a node together with the subtree rooted there. Different occurrences may have identical formula strings.
The unique readability theorem asserts uniqueness of the outer formation rule and its immediate components in a logical formula. For the fully parenthesized language with negation and implication, every formula is uniquely a variable, a negation of one formula, or an implication between an ordered pair of formulas. It gives a well-defined syntax tree and licenses recursive definitions and structural induction on formulas.
In the grammar , no logical formula is a proper initial segment of another. A recursive parser reads one variable, or a negation followed by one formula, or a parenthesized pair of formulas separated by implication. Structural induction shows that this parser consumes precisely one whole formula. Its deterministic stopping position proves prefix-freeness. Consequently any formula substring in a valid formula coincides with the formula of a syntax subtree.
Consider Python programs
x=2+3*4 and x=(2+3)*4. Operator precedence places multiplication inside the right operand of addition in the first abstract syntax tree. The parentheses instead place addition inside the left operand of multiplication in the second. Their right-hand sides evaluate to and . No rule that simply reads all operators left to right would recover both structures. [ref]https://docs.python.org/3.14/reference/expressions.html#operator-precedence. Python language reference, section 6.17, multiplicative operators bind more tightly than additive operators
Two abstract syntax trees for variable assignment: operator precedence gives
. Details. x=2+3*4 the value , while parentheses give x=(2+3)*4 the value These are schematic views of Python trees:
Module is omitted, and the Add/Mult and Store markers are written inside their owning nodes. In the actual schema, BinOp has left, op and right fields; Assign has a list of targets and a value. Name(id='x', ctx=Store()) marks the name as a variable assignment target. Reading x in a program expression instead uses Load. A variable assignment is a statement, not an equation asserting that two values are equal. [ref]A restricted recursive evaluator can follow those fields. It accepts only integer literal values and binary addition, subtraction and multiplication; the surrounding variable assignment remains a separate action. Using
type(value) is int excludes Boolean constants, even though Python treats bool as a subclass of int.import ast
OPS = {ast.Add: lambda a, b: a + b,
ast.Sub: lambda a, b: a - b,
ast.Mult: lambda a, b: a * b}
def evaluate(node):
if isinstance(node, ast.Constant) and type(node.value) is int:
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in OPS:
return OPS[type(node.op)](evaluate(node.left), evaluate(node.right))
raise ValueError("outside the integer-expression language")
for source in ("x=2+3*4", "x=(2+3)*4"):
tree = ast.parse(source, optimize=0)
statement = tree.body[0]
print(statement.targets[0].id, evaluate(statement.value))
# x 14
# x 20The children in a rooted tree have ordered roles:
left and right cannot be interchanged. For subtraction, 8-3 gives while 3-8 gives . Operator associativity also matters: 8-3-1 parses as (8-3)-1, giving , whereas 8-(3-1) gives . Here the syntax groups operators to the left; this does not assert the mathematical associativity of subtraction. Operator precedence determines grouping, rather than a general permission to reorder execution. For example, Python evaluates the calls in f()+g()*h() in the order f, g, h, although the multiplication result must be ready before the outer addition. [ref]https://docs.python.org/3.14/reference/expressions.html#evaluation-order. Python language reference, sections 6.16 and 6.17: left-to-right evaluation and left grouping of additive operators
An abstract syntax tree traversal systematically visits its nodes. A depth-first traversal of a tree that processes each child before its parent is called postorder. For the program expression
2+3*4, the schematic postorder is 2, 3, 4, Mult, Add. This order lets an evaluator obtain each operand value before applying its operation. A traversal of the entire Python schema additionally visits marker nodes such as Add and Store; this shorter list concerns only the expression nodes drawn in the figures. Visiting an abstract syntax tree is a structural operation, and is not a general model of execution: a conditional may select only one branch, while a structural visitor examines both.An abstract syntax tree transformation replaces or rearranges nodes. It can simplify a program expression, insert instrumentation, or translate a language construct into simpler constructs. When intended to preserve programming language semantics, it must preserve the relevant observable behavior, including values, side effects, and failures. A changed tree can be structurally valid while changing the program's meaning.
Constant folding replaces a program expression whose value is known during translation by a literal value. For
x=2+3*4, first replace the multiplication subtree by Constant(value=12), then replace the addition subtree by Constant(value=14). The variable assignment and its Store target survive: the result still assigns to x. This illustrates why a bottom-up abstract syntax tree traversal is convenient: replacing one child can make its parent eligible for the next replacement.Here is a deliberately small Python transformer. Calling
generic_visit first transforms the children; returning a node replaces the visited node. The location helpers retain or supply the metadata expected for compilation. [ref]ast — Abstract syntax trees, Python 3.14 documentation. NodeTransformer, generic_visit, copy_location and fix_missing_locations
class FoldIntegers(ast.NodeTransformer):
def visit_BinOp(self, node):
self.generic_visit(node)
if (isinstance(node.left, ast.Constant)
and isinstance(node.right, ast.Constant)
and type(node.left.value) is int
and type(node.right.value) is int
and type(node.op) in OPS):
value = OPS[type(node.op)](node.left.value, node.right.value)
return ast.copy_location(ast.Constant(value=value), node)
return node
tree = ast.parse("x=2+3*4", optimize=0)
folded = ast.fix_missing_locations(FoldIntegers().visit(tree))
namespace = {}
exec(compile(folded, "<folded example>", "exec"), namespace)
assert namespace["x"] == 14
assert ast.unparse(folded) == "x = 14"This transformer folds literal integer operands only. It leaves
a+3*4 as a+12, without inventing a value for the program identifier a. It leaves calls intact: replacing 0*f() by 0 could discard a side effect or a failure. Nor does it reassociate floating-point arithmetic, where changing parentheses can change rounding. For the supported integer arithmetic, a short structural induction explains correctness: a retained literal value has the same value; at each folded binary node, the already-correct child values are combined by exactly the original operation in the original left/right order. This claim concerns the supported fragment's values, not unrestricted equivalence of arbitrary Python programs.An abstract syntax tree can retain source locations even while omitting punctuation nodes. Python records one-based line numbers and zero-based UTF-8 byte offsets, with the end offset exclusive. In
x=2+3*4, the multiplication node spans offsets through , and ast.get_source_segment returns 3*4. A copied location on a folded 12 describes the original span, not text newly present in the source. Such metadata supports error messages and editing tools without making an abstract syntax tree a lossless record of formatting. [ref]ast — Abstract syntax trees, Python 3.14 documentation. Node classes: lineno, col_offset, end_lineno and end_col_offset; get_source_segment and copy_location
// Target: computer-science.bigb
The rules for forming programs in a programming language. A parser checks and structures text according to these rules; an abstract syntax tree records the resulting constructs.
A language construct defined by expansion into other constructs. Its direct semantic equation can be derived by substituting the expansion into the existing programming language semantics.
Recognition of lexical tokens in program text before or during parsing.
A categorized piece of program text, such as a program identifier, a numeral denoting a literal value, or an operator symbol. Its spelling and category help a parser recognize the larger construct.
A parser recognizes how text fits a programming language syntax and can construct a parse tree or abstract syntax tree.
The recognition process performed by a parser, producing a structural description of text according to a programming language syntax.
A name used by a program, such as
x in a variable assignment. An abstract syntax tree can record the name without determining which value it denotes.A value written directly in program text, such as an integer numeral or a quoted string, rather than obtained through a program identifier. Distinct spellings can denote the same value.
A program construct that is evaluated to obtain a value, potentially with side effects or failure. An arithmetic mathematical expression is one example; its abstract syntax tree records how operands and operations nest.
The syntactic priority that resolves grouping when different operators occur together without parentheses. It determines the abstract syntax tree shape before evaluation.
The syntactic grouping convention for successive operators of the same precedence. Left grouping of subtraction makes
a-b-c mean (a-b)-c; it does not make subtraction an associative operation.A program action that associates a value with a target name. For Python
x=2+3*4, evaluate the right-hand program expression and bind x to its result. [ref]https://docs.python.org/3.14/reference/simple_stmts.html#assignment-statements. Python language reference, section 7.2: assignment to an identifier and evaluation of the right-hand side
For an update , compute from , the values before any mutation. Stable snapshots ensure self-addition doubles the old value and self-subtraction produces zero. Building a replacement representation privately and committing it once can additionally preserve the receiver if validation or checked arithmetic fails. This makes the meaning of an update independent of iteration order and aliasing between its operands.
The meaning of constructs in a programming language, including their permitted values and execution behavior. Programming language syntax organizes constructs; a type system and execution rules give further constraints and meaning.
A program variable is a named binding or storage abstraction used to supply a value during execution of a computer program. Its precise meaning belongs to the programming language semantics: some languages describe mutable storage locations, while others emphasize names associated with values. The current semantic environment and program state determine what an occurrence denotes. A mathematical variable and a program variable consequently need not obey the same rules.
For example, in Python, executing
x = 3 followed by x = x + 1 first evaluates the right-hand program expression using the old binding and then binds x to the resulting integer 4. This variable assignment is a change in the program state, not the equation .[ref]Simple statements, Python 3.14 language reference. §7.2, Assignment statements, evaluation and identifier targets
Binding a second name does not necessarily copy the underlying data. After
a = list() and b = a, executing b.append(7) changes the list also reached through a. By contrast, b = list() rebinds only b. Distinguishing changes to data from changes to names makes shared mutable structures easier to reason about.[ref]Simple statements, Python 3.14 language reference. §7.2, rebinding names versus modifying mutable objects
A local variable is a variable whose binding belongs to a limited program region, such as a procedure invocation or block. The language's scope rules determine where its name denotes that binding. Its storage need not be a fixed physical location: a compiler can use processor registers or eliminate storage when permitted by the programming language semantics.
For example, a recursive procedure can have a separate local accumulator for each invocation, even though every invocation uses the same source-level name. A nested function may retain access to a binding through a programming closure. Scope and lifetime must consequently be distinguished. In Python, binding a name anywhere in a function block normally makes it local throughout that block unless a
global or nonlocal declaration applies; using it before it has a value raises an error.[ref]Undefined behavior is behavior for which a programming language specification imposes no requirements when a specified erroneous condition occurs. It is not a promise to select one arbitrary but otherwise constrained result. The C programming language uses this category for conditions including signed integer overflow.[ref]
For example, evaluating
x+1 as signed int when x is the largest representable int has undefined behavior in that model. A compiler can therefore reason that x+1 exceeds x on executions where the addition is defined, instead of preserving an assumed wraparound case. Unsigned integer arithmetic in C has different rules. Observing a particular result in one build is insufficient to establish a contract; correctness needs range checks, suitable representations or another explicitly defined operation.A mapping from identifiers to their semantic values. A programming closure retains its defining semantic environment; extending it for parameters preserves lexical scope and lets those parameters shadow outer bindings.
A representation of the rest of a computation. In continuation-passing style, a computation receives a function telling it how to use its result. An explicit computer memory argument can be supplied when the continuation is invoked, so capturing control need not capture a snapshot of computer memory.
A computation that can suspend and later resume. A first-class continuation can represent its suspended control state while mutable computer memory remains shared.
Tasks transfer control at explicit suspension points. A FIFO queue of runnable continuations implements round-robin scheduling; a task that never transfers control can prevent others from running.
A continuation represented as an ordinary language value that can be stored and later invoked. Whether it may be invoked once or repeatedly, and whether mutable program state is restored, are separate semantic choices.
Supply the current continuation to a user function. A language can expose this as an escape function or as a separate continuation value with its own invocation primitive; those interfaces need corresponding semantic definitions.
Articles were limited to the first 100 out of 323 total.
Articles by others on the same topic
There is only space for two languages at most in the world: the compiled one, and the interpreted one.
Those two are languages not by any means perfect from a language design point of view, and there are likely already better alternatives, they are only chosen due to a pragmatic tradeoff between ecosystem and familiarity.
Ciro predicts that Python will become like Fortran in the future: a legacy hated by most who have moved to JavaScript long ago (which is slightly inferior, but too similar, and with too much web dominance to be replaced), but with too much dominance in certain applications like machine learning to be worth replacing, like Fortran dominates certain HPC applications. We'll see. Maybe non performance critical scripting languages are easier to replace.
C++ however is decent, and is evolving in very good directions in the 2010's, and will remain relevant in the foreseeable future.
Bash can also be used when you're lazy. But if the project goes on, you will sooner or later regret that choice.
The language syntax in itself does not matter. All that matters is how many useful libraries and tooling it has.
This is how other languages compare:
- C: but cannot make a large codebase DRY without insanity
- Ruby: the exact same as Python, and only strong in one domain: web development, while Python rules everything else, and is not bad on web either. So just kill Ruby, please.
- JavaScript: it is totally fine if Node.js destroys Python and becomes the ONE scripting language to rule them all since Python and JavaScript are almost equally crappy (although JavaScript is a bit more of course).One thing must be said tough:
someobject.not_defined_propertysilently returningundefinedrather than blowing up is bullshit. - Go: likely a good replacement for Python. If the ecosystem gets there, will gladly use it more.
- Java: good language, but has an ugly enterprisey ecosystem, Oracle has made/kept the development process too closed, and API patenting madness on Android just kills if off completely
- Haskell: many have tried to learn some functional stuff, but too hard. Sounds really cool though.
- Rust: sounds cool, you will gladly replace C and C++ with it if the ecosystem ramps up.
- C: Microsoft is evil
- Tcl, Perl: Python killed them way back and is less insane
- R, GNU Octave and any other "numerical computing language": all of this is a waste of society's time as explained at: Section "Numerical computing language"
- Swift: Ciro would rather stay away from Apple dominated projects if possible since they sell a closed source operating system

