从函数A返回随机值副作用? [英] Is Returning A Random Value From Function A Side Effect?

查看:94
本文介绍了从函数A返回随机值副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些F#代码,我正在研究一个函数来从一组字符串中返回一个随机字符串。假设我有这样的事情:

 打开系统

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

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

let resultstring = rstring a ;;

我的问题是这样的:我对函数式编程概念的理解是,如果给定的函数具有相同的输入每次它应该总是返回相同的输出。那么在这种特殊情况下,每次出现副作用时都会返回一个不同的字符串?我只是好奇。



如果这是一个重复的问题,请将我指向原始文件,然后关闭它。我不知道我会用什么搜索字符串来查找与此相关的任何问题。






编辑:谢谢所有的信息每个人。我似乎将参照透明度和缺乏副作用的概念混为一谈。所以,非常感谢所有人为我设定了不同的答案,并感谢您的回答。


$ b

函数可以从同一个输入返回不同值的唯一方法是通过副作用。其他人可能会声明,但他们是错误的。



<您可以声称'读取系统时间'(显然是基于效果)不是一个效果。根据这个定义,这不是一个副作用,但这个定义没有用,因为人们关心副作用的唯一原因是因为它们影响了参照透明度,换言之,参照透明是唯一重要的,这个功能显然不是透明的。)


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.

解决方案

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.)

这篇关于从函数A返回随机值副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆