fbpx
Wikipedia

Guard (computer science)

In computer programming, a guard is a boolean expression that must evaluate to true if the execution of the program is to continue in the branch in question. Regardless of which programming language is used, a guard clause, guard code, or guard statement, is a check of integrity preconditions used to avoid errors during execution.

Uses edit

A typical example is checking that a reference about to be processed is not null, which avoids null-pointer failures.

Other uses include using a boolean field for idempotence (so subsequent calls are nops), as in the dispose pattern.

public string Foo(string username) {  if (username == null) {  throw new ArgumentNullException(nameof(username), "Username is null.");  }  // Rest of the method code follows here... } 

Flatter code with less nesting edit

The guard provides an early exit from a subroutine, and is a commonly used deviation from structured programming, removing one level of nesting and resulting in flatter code:[1] replacing if guard { ... } with if not guard: return; ....

Using guard clauses can be a refactoring technique to improve code. In general, less nesting is good, as it simplifies the code and reduces cognitive burden.

For example, in Python:

# This function has no guard clause def f_noguard(x): if isinstance(x, int): #code #code #code return x + 1 else: return None # Equivalent function with a guard clause. Note that most of the code is less indented, which is good def f_guard(x): if not isinstance(x, int): return None #code #code #code return x + 1 

Another example, written in C:

// This function has no guard clause int funcNoGuard(int x) {  if (x >= 0) {  //code  //code  //code  return x + 1;   } else {  return 0;  } } // Equivalent function with a guard clause int funcGuard(int x) {  if (x < 0) {  return 0;  }  //code  //code  //code  return x + 1;  } 

Terminology edit

The term is used with specific meaning in APL, Haskell, Clean, Erlang, occam, Promela, OCaml, Swift,[2] Python from version 3.10, and Scala programming languages.[citation needed] 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.

Mathematics edit

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:

 

In this case the guards are in the "if" and "otherwise" clauses.

Multiple guards edit

If there are several parallel guards, 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.

Evolution edit

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 

In 1966 ISWIM 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.

KRC, a "miniaturized version"[3] of SASL (1976), was one of the first programming languages to use the term "guard". Its function definitions could have several clauses, and the one to apply was chosen based on the guards that followed each clause:

 fac n = 1, n = 0  = n * fac (n-1), n > 0 

Use of guard clauses, and the term "guard clause", dates at least to Smalltalk practice in the 1990s, as codified by Kent Beck.[1]

In 1996, Dyalog APL adopted an alternative pure functional style in which the guard is the only control structure.[4] This example, in APL, computes the parity of the input number:

parity{  2 : 'odd'  'even'  } 

Pattern guard edit

In addition to a guard attached to a pattern, pattern guard can refer to the use of pattern matching in the context of a guard. In effect, a match of the pattern is taken to mean pass. This meaning was introduced in a proposal for Haskell by Simon Peyton Jones titled in April 1997 and was used in the implementation of the proposal. The feature provides the ability to use patterns in the guards of a pattern.

An example in 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 the lookups of the variables from the environment produce values, is the sum of the values. ..." As in list comprehensions, the guards are in series, and if any of them fails the branch is not taken.

See also edit

References edit

  1. ^ a b Beck, Kent (1997). "Guard Clause". Smalltalk Best Practice Patterns,. pp. 178–179.
  2. ^ Cook, Nate. "guard & defer". NSHipster. Retrieved 2016-02-26.
  3. ^ Turner, D. A. "Some History of Functional Programming Languages" (PDF).
  4. ^ Scholes, John. "Direct Functions in Dyalog APL" (PDF).

External links edit

  • Guard in Free On-Line Dictionary of Computing - FOLDOC, Denis Howe (editor).
  • Guard Clause, WikiWikiWeb
  • The Haskell 98 Report, chapter 3 Expressions.
  • The Mathematica Book, section
  • The Glorious Glasgow Haskell Compilation System User's Guide, Version 6.4, section

guard, computer, science, this, article, includes, list, general, references, lacks, sufficient, corresponding, inline, citations, please, help, improve, this, article, introducing, more, precise, citations, september, 2010, learn, when, remove, this, template. This article includes a list of general references but it lacks sufficient corresponding inline citations Please help to improve this article by introducing more precise citations September 2010 Learn how and when to remove this template message In computer programming a guard is a boolean expression that must evaluate to true if the execution of the program is to continue in the branch in question Regardless of which programming language is used a guard clause guard code or guard statement is a check of integrity preconditions used to avoid errors during execution Contents 1 Uses 1 1 Flatter code with less nesting 2 Terminology 3 Mathematics 4 Multiple guards 5 Evolution 6 Pattern guard 7 See also 8 References 9 External linksUses editA typical example is checking that a reference about to be processed is not null which avoids null pointer failures Other uses include using a boolean field for idempotence so subsequent calls are nops as in the dispose pattern public string Foo string username if username null throw new ArgumentNullException nameof username Username is null Rest of the method code follows here Flatter code with less nesting edit The guard provides an early exit from a subroutine and is a commonly used deviation from structured programming removing one level of nesting and resulting in flatter code 1 replacing if guard with if not guard return Using guard clauses can be a refactoring technique to improve code In general less nesting is good as it simplifies the code and reduces cognitive burden For example in Python This function has no guard clause def f noguard x if isinstance x int code code code return x 1 else return None Equivalent function with a guard clause Note that most of the code is less indented which is good def f guard x if not isinstance x int return None code code code return x 1 Another example written in C This function has no guard clause int funcNoGuard int x if x gt 0 code code code return x 1 else return 0 Equivalent function with a guard clause int funcGuard int x if x lt 0 return 0 code code code return x 1 Terminology editThe term is used with specific meaning in APL Haskell Clean Erlang occam Promela OCaml Swift 2 Python from version 3 10 and Scala programming languages citation needed 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 Mathematics editIn the following Haskell example the guards occur between each pair of and f x x gt 0 1 otherwise 0 This is similar to the respective mathematical notation f x 1if x gt 00otherwise displaystyle f x left begin matrix 1 amp mbox if x gt 0 0 amp mbox otherwise end matrix right nbsp In this case the guards are in the if and otherwise clauses Multiple guards editIf there are several parallel guards 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 Evolution editA 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 gt 0 gt 1 x 0 x gt 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 gt 0 gt 1 x x lt 0 gt 1 x 0 In 1966 ISWIM 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 KRC a miniaturized version 3 of SASL 1976 was one of the first programming languages to use the term guard Its function definitions could have several clauses and the one to apply was chosen based on the guards that followed each clause fac n 1 n 0 n fac n 1 n gt 0 Use of guard clauses and the term guard clause dates at least to Smalltalk practice in the 1990s as codified by Kent Beck 1 In 1996 Dyalog APL adopted an alternative pure functional style in which the guard is the only control structure 4 This example in APL computes the parity of the input number parity 2 odd even Pattern guard editIn addition to a guard attached to a pattern pattern guard can refer to the use of pattern matching in the context of a guard In effect a match of the pattern is taken to mean pass This meaning was introduced in a proposal for Haskell by Simon Peyton Jones titled A new view of guards in April 1997 and was used in the implementation of the proposal The feature provides the ability to use patterns in the guards of a pattern An example in extended Haskell clunky env var1 var2 Just val1 lt lookup env var1 Just val2 lt lookup env var2 val1 val2 other equations for clunky This would read Clunky for an environment and two variables in case the lookups of the variables from the environment produce values is the sum of the values As in list comprehensions the guards are in series and if any of them fails the branch is not taken See also editAssertion Guarded suspension Iverson bracket Logical conditional Sentinel node an object to represent the end of a data structure Switch statementReferences edit a b Beck Kent 1997 Guard Clause Smalltalk Best Practice Patterns pp 178 179 Cook Nate guard amp defer NSHipster Retrieved 2016 02 26 Turner D A Some History of Functional Programming Languages PDF Scholes John Direct Functions in Dyalog APL PDF External links editGuard in Free On Line Dictionary of Computing FOLDOC Denis Howe editor Guard Clause WikiWikiWeb The Haskell 98 Report chapter 3 Expressions The Mathematica Book section 2 3 5 Putting Constraints on Patterns The Glorious Glasgow Haskell Compilation System User s Guide Version 6 4 section 7 3 2 Pattern guards Retrieved from https en wikipedia org w index php title Guard computer science amp oldid 1210889435, wikipedia, wiki, book, books, library,

article

, read, download, free, free download, mp3, video, mp4, 3gp, jpg, jpeg, gif, png, picture, music, song, movie, book, game, games.