In computer programming, a
guard is a
booleanIn computer science, the Boolean or logical data type is a primitive data type having one of two values: true or false, intended to represent the truth values of logic and Boolean algebra....
expressionAn expression in a programming language is a combination of values, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value...
that must evaluate to true if the program execution is to continue in the branch in question. The term is used at least in
HaskellHaskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry.- History :...
,
CleanIn computer science, Clean is a general-purpose purely functional computer programming language.- Features :The language Clean first appeared in 1987 and is still further developed; it shares many properties with Haskell:...
,
ErlangErlang is a general-purpose concurrent programming language andruntime system. The sequential subset of Erlang is a functional language, with strict evaluation, single assignment, and dynamic typing. For concurrency it follows the Actor model. It was designed by Ericsson to support distributed,...
,
occamoccam is a concurrent programming language that builds on the Communicating Sequential Processes process algebra, and shares many of its features. It is named after William of Ockham of Occam's Razor fame....
,
PromelaPROMELA is a verification modeling language. The language allows for the dynamic creation of concurrent processes to model, for example, distributed systems. In PROMELA models, communication via message channels can be defined to be synchronous , or asynchronous...
and OCaml programming languages. In
MathematicaMathematica is a computational software program used in scientific, engineering, and mathematical fields and other areas of technical computing...
, guards are called
constraints. Guards are the fundamental concept in
Guarded Command LanguageThe Guarded Command Language is a language defined by Edsger Dijkstra for predicate transformer semantics . It combines programming concepts in a compact way, before the program is written in some practical programming language...
, a language in
formal methodsIn computer science and software engineering, formal methods are a particular kind of mathematically-based techniques for the specification, development and verification of software and hardware systems...
. Guards can be used to augment
pattern matchingIn computer science, pattern matching is the act of checking for the presence of the constituents of a given pattern. In contrast to pattern recognition, the pattern is rigidly specified. Such a pattern concerns conventionally either sequences or tree structures...
with the possibility to skip a pattern even if the structure matches.
In computer programming, a
guard is a
booleanIn computer science, the Boolean or logical data type is a primitive data type having one of two values: true or false, intended to represent the truth values of logic and Boolean algebra....
expressionAn expression in a programming language is a combination of values, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value...
that must evaluate to true if the program execution is to continue in the branch in question. The term is used at least in
HaskellHaskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry.- History :...
,
CleanIn computer science, Clean is a general-purpose purely functional computer programming language.- Features :The language Clean first appeared in 1987 and is still further developed; it shares many properties with Haskell:...
,
ErlangErlang is a general-purpose concurrent programming language andruntime system. The sequential subset of Erlang is a functional language, with strict evaluation, single assignment, and dynamic typing. For concurrency it follows the Actor model. It was designed by Ericsson to support distributed,...
,
occamoccam is a concurrent programming language that builds on the Communicating Sequential Processes process algebra, and shares many of its features. It is named after William of Ockham of Occam's Razor fame....
,
PromelaPROMELA is a verification modeling language. The language allows for the dynamic creation of concurrent processes to model, for example, distributed systems. In PROMELA models, communication via message channels can be defined to be synchronous , or asynchronous...
and OCaml programming languages. In
MathematicaMathematica is a computational software program used in scientific, engineering, and mathematical fields and other areas of technical computing...
, guards are called
constraints. Guards are the fundamental concept in
Guarded Command LanguageThe Guarded Command Language is a language defined by Edsger Dijkstra for predicate transformer semantics . It combines programming concepts in a compact way, before the program is written in some practical programming language...
, a language in
formal methodsIn computer science and software engineering, formal methods are a particular kind of mathematically-based techniques for the specification, development and verification of software and hardware systems...
. Guards can be used to augment
pattern matchingIn computer science, pattern matching is the act of checking for the presence of the constituents of a given pattern. In contrast to pattern recognition, the pattern is rigidly specified. Such a pattern concerns conventionally either sequences or tree structures...
with the possibility to skip a pattern even if the structure matches. Boolean expressions in
conditional statementIn computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false...
s usually also fit this definition of a guard although they are called
conditions.
In the following Haskell example, the guards occur between each pair of "|" and "=":
f x
| x > 0 = 1
| otherwise = 0
This is similar to the respective mathematic notation:
In this case the guards are in the "if" and "otherwise" clauses.
If there are several parallel guards, such as in the example above, they are normally tried in a top to bottom order and the branch of the first to pass is chosen. Guards in a list of cases are typically parallel.
However, in Haskell
list comprehensions the guards are in series, and if any of them fails, the list element is not produced. This would be the same as combining the separate guards with
logical ANDIn logic and mathematics, logical conjunction or and is a two-place logical connective that has the value true if both of its operands are true, otherwise a value of false.-Notation:...
, except that there can be other list comprehension clauses among the guards.
Evolution
A simple conditional expression, already present in CPL in 1963, has a guard on first sub-expression, and another sub-expression to use in case the first one cannot be used. Some common ways to write this:
(x>0) -> 1/x; 0
x>0 ? 1/x : 0
If the second sub-expression can be a further simple conditional expression, we can give more alternatives to try before the last
fall-through:
(x>0) -> 1/x; (x<0) -> -1/x; 0
Already
ISWIMISWIM is an abstract computer programming language devised by Peter J. Landin and first described in his article, The Next 700 Programming Languages, published in the Communications of the ACM in 1966...
in 1966 had a form of conditional expression without an obligatory fall-through case, thus separating guard from the concept of choosing either-or. In the case of ISWIM, if none of the alternatives could be used, the value was to be
undefined, which was defined to never compute into a value.
SASLSASL is a purely functional programming language developed by David Turner at the University of St Andrews in 1972, based on the applicative subset of ISWIM. In 1976 Turner redesigned and reimplemented it as a non-strict language...
(1976) was one of the first programming languages to use the term "guard". In the language, functions could have several definitions and the one to apply was chosen based on the guards that followed each definition:
fac n = 1, n = 0
= n * fac (n-1), n > 0
Pattern guard
In addition to a guard attached to a pattern,
pattern guard can refer to the use of pattern matching in context of a guard. In effect, a match of the pattern is taken to mean pass. This meaning was introduced by a proposal for Haskell by
Simon Peyton JonesSimon Peyton Jones is a British computer scientist who researches the implementation and applications of functional programming languages, particularly lazy functional languages...
titled
A new view of guards in April 1997 and has been further used about the implementation of the proposal. The feature provides the possibility to use patterns in the guards of a pattern.
An example in the extended Haskell:
clunky env var1 var2
| Just val1 <- lookup env var1
, Just val2 <- lookup env var2
= val1 + val2
-- ...other equations for clunky...
This would read: "Clunky for an environment and two variables,
in case that the lookups of the variables from the environment produce values, is the sum of the values. ..." Like in
list comprehensions, the guards are in series, and if any of them fails the branch is not taken.