+ 12

Difference between PURE FUNCTION and IMPURE FUNCTION. {DETAIL PLEASE! }

Explain with example in simple language.

9th Nov 2019, 3:25 AM
Reca Resu
Reca Resu - avatar
6 Respostas
+ 8
maybe this will help? it’s written in python but i’m assuming it’s the same idea in java. someone please correct me if i’m wrong. https://code.sololearn.com/cV5aC4X3SqGL/?ref=app
9th Nov 2019, 4:03 AM
꧁àŒș Jenspi àŒ»ê§‚
꧁àŒș Jenspi àŒ»ê§‚ - avatar
+ 5
Thanx Jenny
9th Nov 2019, 4:13 AM
Reca Resu
Reca Resu - avatar
+ 4
for my example, a pure function can be represented as making a new shopping list. when we call the pure function (new_list) and give it an argument (a list of groceries) it will always return a newly created shopping list (our groceries). an impure function can be represented as adding to an existing shopping list. impure functions wont return anything, and will permanently change a variable outside of the function instead.
9th Nov 2019, 4:12 AM
꧁àŒș Jenspi àŒ»ê§‚
꧁àŒș Jenspi àŒ»ê§‚ - avatar
+ 4
Pure funcs return a value and produce no side effects I.e. they make no changes to variables other than the one passed to it. Impure functions don't return a value. E.g. printing to screen. And may change some global vars
9th Nov 2019, 8:54 AM
Logomonic Learning
Logomonic Learning - avatar
9th Nov 2019, 4:17 AM
Avinesh
Avinesh - avatar
+ 3
A pure function will always return the same value when given the same arguments and its execution cannot change anything by any means other than returning a value. An impure function violates one or both of these rules. For example, printing to the console is impure because it changes something (the console) by a means other than returning a value (it actually returns no value). Another impure function would be getTime() (or the equivalent in a given language) because it accepts no arguments but returns a different value (the current time) every time you call it (gives different return values for the same set of arguments, which happens to be no arguments, in this case). Pure functions are useful because you can rely on them not changing anything when you call them and the value they return depending only on the arguments you pass to the function (can’t be changed by external code or factors such as how many times you’ve called the function).
11th Nov 2019, 2:34 AM
Jason Stone
Jason Stone - avatar