Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d
d programming
pure
pure functions
communitycreator

What are pure functions in D?

Chinweuba Elijah Azubuike

Overview

In D, pure functions have the following properties that separate them from other functions:

  • They are preceded with the pure keyword during declaration.

  • They have global and static mutable state restrictions.

  • They can only call pure functions and can override impure functions.

  • They can modify the local state of a function.

Importance of pure functions

Pure functions do not have an external connection. When we’re debugging them, we don’t have to worry about their interaction with the entire application code.

Example

import std.stdio; 

 int g = 45; 
 int h = 30; 
  

pure int purefunc( int x,int y) { 
  int i = x*y;
        // Can use the new expression: 
   return i; 
}

void main() { 
   writeln("the product of x and y : ",purefunc(g,h)); 
}
D pure function

Explanation

We built a simple function to multiply two variables.

Line 3–4: We declare and initialize our variables.

Line 7: We declare our pure function using the pure keyword and we pass parameters to it.

Line 8: We multiplying x by y which are the arguments of the function.

Line 10: We return i which is the product of x and y.

Line 13–15: We print the output to the screen by calling the pure function.

RELATED TAGS

d
d programming
pure
pure functions
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring