Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Returning A Random Value From Function A Side Effect?

I was working on some F# code and I was working on a function to return a random string from a set of strings. Let's say I had something like this:

open System

let a = [|"a";"b";"c";"d"|]

let rstring (arr:string[]) =
   let r = new Random()
   arr.[r.Next(0,3)]

let resultstring = rstring a;;

My question is this: My understanding of the notion of functional programming is that if a given function has the same input each time it should always return the same output. So in this particular case is returning a different string each time a "side effect"? I'm just curious.

If this is a duplicate question, just point me to the original and I'll close this. I'm not sure what search string I would use to find any questions related to this one.


EDIT: Thanks for all the information everyone. It seems that I conflated the concepts of referential transparency and the lack of side-effects. So, thanks all for setting me straight on the difference and thanks for your answers.

like image 684
Onorio Catenacci Avatar asked Dec 08 '10 19:12

Onorio Catenacci


2 Answers

Yes.

The only way that a function can return different values from the same input is via side effects. Other people may claim otherwise, but they are wrong.

(You can claim that 'reading the system time' (which is clearly based on effects) is not an effect. By this definition, it's not a side-effect. But that definition is not useful, since the only reason people "care" about side-effects is because they affect referential transparency. In other words, referential transparency is the only thing that matters, and this function is clearly not referentially transparent.)

like image 197
Brian Avatar answered Oct 07 '22 12:10

Brian


"Side effect" means that some state is changed by the function, not that the return value differs. In your case, the function is doing both - it is changing the state of the PRNG and return a different value.

Edit:

I'll also add that if a function always returns the same value for a given input it is called idempotent. Also "side effect" includes functions that read from an external state. For example:

int global = 0;
int function()
{
  return global;
}

has side effects.

like image 26
Niki Yoshiuchi Avatar answered Oct 07 '22 13:10

Niki Yoshiuchi