HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, a semipredicate problem occurs when a
subroutine In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. Functions may ...
intended to return a useful value can fail, but the signalling of failure uses an otherwise valid
return value In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after the instruction which called the subroutine, known as its return address. The return address is s ...
. The problem is that the caller of the subroutine cannot tell what the result means in this case.


Example

The
division Division or divider may refer to: Mathematics *Division (mathematics), the inverse of multiplication *Division algorithm, a method for computing the result of mathematical division Military *Division (military), a formation typically consisting ...
operation yields a
real number In mathematics, a real number is a number that can be used to measure a ''continuous'' one-dimensional quantity such as a distance, duration or temperature. Here, ''continuous'' means that values can have arbitrarily small variations. Every ...
, but fails when the divisor is
zero 0 (zero) is a number representing an empty quantity. In place-value notation such as the Hindu–Arabic numeral system, 0 also serves as a placeholder numerical digit, which works by Multiplication, multiplying digits to the left of 0 by th ...
. If we were to write a function that performs division, we might choose to return 0 on this invalid input. However, if the dividend is 0, the result is 0 too. This means there is no number we can return to uniquely signal attempted division by zero, since all real numbers are in the range of division.


Practical implications

Early programmers dealt with potentially exceptional cases, as in the case of division, using a convention that required the calling routine to check the validity of the inputs before calling the division function. This had two problems. First, it greatly encumbers all code that performs division (a very common operation). Second, it violates the
Don't repeat yourself "Don't repeat yourself" (DRY) is a principle of software development aimed at reducing repetition of software patterns, replacing it with abstractions or using data normalization to avoid redundancy. The DRY principle is stated as "Every piece of ...
and encapsulation principles, where the former is about eliminating duplicated code, and the latter suggests that data associated code should be contained in one place (in this case the verification of input was done separately). If we imagine a more complicated computation than division, it could be hard for the caller to know what is considered invalid input; in some cases figuring out whether the input is valid may be as costly as performing the entire computation. There's also the possibility of the target function being modified and then expecting different preconditions than the ones the caller has checked for; such a change would require changes in all the places where the function was called from.


Solutions

The semipredicate problem is not universal among functions that can fail.


Using a custom convention to interpret return values

If the function's range does not cover the entire
space Space is the boundless three-dimensional extent in which objects and events have relative position and direction. In classical physics, physical space is often conceived in three linear dimensions, although modern physicists usually consi ...
corresponding to the
data type In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
of the function's return value, a value known to be impossible under normal computation can be used. For example, consider the function index, which takes a string and a substring, and returns the
integer An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the languag ...
index of the substring in the main string. If the search fails, the function may be programmed to return -1 (or any other negative value), since this can never signify a successful result. This solution has its problems, though, as it overloads the natural meaning of a function with an arbitrary convention. * The programmer must remember specific failure values for many functions, which of course cannot be identical if the functions have different ranges. * A different
implementation Implementation is the realization of an application, or execution of a plan, idea, model, design, specification, standard, algorithm, or policy. Industry-specific definitions Computer science In computer science, an implementation is a real ...
of the same function may choose to use a different failure value, resulting in possible bugs when programmers move from environment to environment. * If the failing function wishes to communicate useful information about why it had failed, one failure value is insufficient. * A signed integer halves the possible index range to be able to store the
sign bit In computer science, the sign bit is a bit in a signed number representation that indicates the sign of a number. Although only signed numeric data types have a sign bit, it is invariably located in the most significant bit position, so the term ...
. * While the chosen value is an invalid result for this operation, it might be a valid input to followup operations. For example in Python str.find returns -1 if the substring is not found, but -1 is a valid index (negative indices generally start from the end).


Multivalued return

Many languages allow, through one mechanism or another, a function to return multiple values. If this is available, the function can be redesigned to return a boolean value signalling success or failure, in addition to its primary return value. If multiple error modes are possible, the function may instead return an enumerated return code (error code) in addition to its primary return value. Various techniques for returning multiple values include: * Returning a
tuple In mathematics, a tuple is a finite ordered list (sequence) of elements. An -tuple is a sequence (or ordered list) of elements, where is a non-negative integer. There is only one 0-tuple, referred to as ''the empty tuple''. An -tuple is defi ...
of values. This is conventional in languages such as Python, that have a built-in tuple data type, and special syntax for handling these: in Python, calls the function which returns a pair of values, and assigns the elements of the pair to two variables. * Secondary return values as in
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
. All expressions have a primary value, but secondary values might be returned to interested callers. For example, the GETHASH function returns the value of the given key in an associative map, or a default value otherwise. However, it also returns a secondary boolean indicating whether the value was found, making it possible to distinguish between the "no value was found" and "the value found was equal to default value" cases. This is different from returning a tuple, in that secondary return values are ''optional'' – if a caller does not care about them, it may ignore them completely, whereas tuple-valued returns are merely
syntactic sugar In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
for returning and unpacking a list, and ''every'' caller must always know about and consume all items returned. * Languages with
call by reference In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the f ...
– or equivalents, such as
call by address In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the f ...
using pointers – can allow for multivalued return by designating some parameters as output parameters. In this case, the function could just return the error value, with a variable intended to store the actual result being passed to the function. This is analogous to the use of an
exit status The exit status of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task. In DOS, this may be referred ...
to store an error code, and streams for returning content. * A variant of output parameters is used in object-oriented languages that use
call by sharing In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the ...
, where a mutable object is passed to a function, and the object is mutated to return values. *
Logic programming Logic programming is a programming paradigm which is largely based on formal logic. Any program written in a logic programming language is a set of sentences in logical form, expressing facts and rules about some problem domain. Major logic pro ...
languages such as
Prolog Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
have no return values. Instead, unbound logical variables are used as output parameters, to be unified with values constructed in a predicate call.


Global variable for return status

Similar to an "out" argument, a
global variable In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the ''global environment'' or ''global s ...
can store what error occurred (or simply whether an error occurred). For instance, if an error occurs, and is signalled (generally as above, by an illegal value like −1) the Unix
errno errno.h is a header file in the standard library of the C programming language. It defines macros for reporting and retrieving error conditions using the symbol errno (short for "error number").International Standard for Programming Language C ( ...
variable is set to indicate which value occurred. Using a global has its usual drawbacks:
thread safety Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without un ...
becomes a concern (modern operating systems use a thread-safe version of errno), and if only one error global is used, its type must be wide enough to contain all interesting information about all possible errors in the system.


Exceptions

Exceptions are one widely used scheme for solving this problem. An error condition is not considered a return value of the function at all; normal
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
is disrupted and explicit handling of the error takes place automatically. They are an example of out-of-band signalling.


Expanding the return value type


Manually created hybrid types

In C, a common approach, when possible, is to use a data type deliberately wider than strictly needed by the function. For example, the standard function getchar() is defined with return type int and returns a value in the range ,255(the range of unsigned char) on success or the value EOF ( implementation-defined, but outside the range of unsigned char) on the end of the input or a read error.


Nullable reference types

In languages with pointers or references, one solution is to return a pointer to a value, rather than the value itself. This return pointer can then be set to
null Null may refer to: Science, technology, and mathematics Computing * Null (SQL) (or NULL), a special marker and keyword in SQL indicating that something has no value * Null character, the zero-valued ASCII character, also designated by , often use ...
to indicate an error. It is typically suited to functions that return a pointer anyway. This has a performance advantage over the OOP style of exception handling,Why Exceptions should be Exceptional - an example of performance comparison
/ref> with the drawback that negligent programmers may not check the return value, resulting in a
crash Crash or CRASH may refer to: Common meanings * Collision, an impact between two or more objects * Crash (computing), a condition where a program ceases to respond * Cardiac arrest, a medical condition in which the heart stops beating * Couch ...
when the invalid pointer is used. Whether a pointer is null or not is another example of the predicate problem; null may be a flag indicating failure or the value of a pointer returned successfully. A common pattern in the
UNIX Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, ...
environment is setting a separate variable to indicate the cause of an error. An example of this is the
C standard library The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. ISO/IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the original ANSI C standard, it was ...
fopen() function.


Implicitly hybrid types

In dynamically-typed languages, such as PHP and
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lispin ...
, the usual approach is to return "false", "none" or "null" when the function call fails. This works by returning a different type to the normal return type (thus expanding the type). It is a dynamically-typed equivalent to returning a null pointer. For example, a numeric function normally returns a number (int or float), and while zero might be a valid response; false is not. Similarly, a function that normally returns a string might sometimes return the empty string as a valid response, but return false on failure. This process of type-juggling necessitates care in testing the return value: e.g. in PHP, use

(i.e. equal and of same type) rather than just

(i.e. equal, after automatic type-conversion). It works only when the original function is not meant to return a boolean value, and still requires that information about the error be conveyed via other means.


Explicitly hybrid types

In
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
and other
functional programming language In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
s, it is common to use a data type that is just as big as it needs to be to express any possible result. For example, we could write a division function that returned the type Maybe Real, and a getchar function returning Either String Char. The first is an option type, which has only one failure value, Nothing. The second case is a
tagged union In computer science, a tagged union, also called a variant, variant record, choice type, discriminated union, disjoint union, sum type or coproduct, is a data structure used to hold a value that could take on several different, but fixed, types. O ...
: a result is either some string with a descriptive error message, or a successfully read character. Haskell's
type inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
system helps ensure that callers deal with possible errors. Since the error conditions become explicit in the function type, looking at its signature immediately tells the programmer how to treat errors. In addition, tagged unions and option types form monads when endowed with appropriate functions: this may be used to keep the code tidy by automatically propagating unhandled error conditions.


See also

*
Null-terminated string In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character (a character with a value of zero, called NUL in this article). Alternative names are C str ...
*
Nullable type Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type. In statically typed languages, a nullable type is an option type, while in ...
* Option type *
Sentinel value In computer programming, a sentinel value (also referred to as a flag value, trip value, rogue value, signal value, or dummy data) is a special value in the context of an algorithm which uses its presence as a condition of termination, typically in ...
*
Tagged union In computer science, a tagged union, also called a variant, variant record, choice type, discriminated union, disjoint union, sum type or coproduct, is a data structure used to hold a value that could take on several different, but fixed, types. O ...


References

{{DEFAULTSORT:Semipredicate Problem Programming language topics