+ 12
Difference between PURE FUNCTION and IMPURE FUNCTION. {DETAIL PLEASE! }
Explain with example in simple language.
6 odpowiedzi
+ 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
+ 5
Thanx Jenny
+ 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.
+ 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
+ 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).