Guard (computer Science)

Guard (computer Science)

In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question. The term is used at least in Haskell, Clean, Erlang, occam, Promela, OCaml and Scala programming languages. In Mathematica, guards are called constraints. Guards are the fundamental concept in Guarded Command Language, a language in formal methods. Guards can be used to augment pattern matching with the possibility to skip a pattern even if the structure matches. Boolean expressions in conditional statements 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 mathematical notation:


f(x) = \left\{ \begin{matrix} 1 & \mbox{if } x>0 \\ 0 & \mbox{otherwise} \end{matrix} \right.

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 AND, except that there can be other list comprehension clauses among the guards.

Read more about Guard (computer Science):  Evolution, Pattern Guard

Famous quotes containing the word guard:

    What is the structure of government that will best guard against the precipitate counsels and factious combinations for unjust purposes, without a sacrifice of the fundamental principle of republicanism?
    James Madison (1751–1836)