如果它从外部读取一些数据而不是参数,它是一个纯函数吗? [英] Is it a pure function if it reads some data from outside rather than parameters?

查看:164
本文介绍了如果它从外部读取一些数据而不是参数,它是一个纯函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala函数式编程一书中,它提供了一些关于副作用的例子,如:


  • 修改变量

  • 修改数据结构

  • 在对象上设置一个字段
  • 抛出一个异常或暂停出现错误打印到控制台或阅读用户输入

  • 读取或写入文件
  • 在屏幕上绘图



  • 我的问题是,从外部读取一些数据比参数使得函数不纯吗?

    Eg

      val name =Scala

    def upcase()= name.toUpperCase

    upcase 函数是否为纯函数?






    编辑:按照此答案: https://stackoverflow.com/a/31377452/342235 ,我的功能实际上不是功能,它是一种方法,所以我给一个函数版本,并询问相同的问题:

      val name =Scala

    val upcase:()=> String =()=> name.toUpperCase


    解决方案

    数据不是不纯;该函数每次仍会返回相同的值。如果 name var ,那么这个函数将是不纯的,因为外部的东西可能会改变名称,因此对 upcase()的多次调用可能会计算出不同的值。

    (当然,也可以通过反射来改变 name 。我们只能谈论关于什么样的函数可以调用给定函数的一些概念的纯度,以及我们认为什么样的副作用是等价的)

    值得注意的是你的函数不是纯粹的,因为 toUpperCase 不纯;它取决于系统的默认语言环境,并且可能在不同的系统上产生不同的结果(例如在土耳其语系统上,i.toUpperCase ==İ)。你应该总是传递一个明确的 Locale ,例如 def upcase()= name.toUpperCase(Locale.ENGLISH);那么该函数将是纯粹的。


    In the book of "functional programming in Scala", it gives some examples about side-effects, like:

    • Modifying a variable
    • Modifying a data structure in place
    • Setting a field on an object
    • Throwing an exception or halting with an error  Printing to the console or reading user input
    • Reading from or writing to a file
    • Drawing on the screen

    My question is, is reading some data from outside rathen than the parameters makes the function impure?

    E.g.

    val name = "Scala"
    
    def upcase() = name.toUpperCase
    

    Is the upcase function pure or not?


    Edit: as per this answer: https://stackoverflow.com/a/31377452/342235, my "function" is not actually function, it's a method, so I give a function version of it, and ask the same question:

    val name = "Scala"
    
    val upcase: () => String = () => name.toUpperCase
    

    解决方案

    Reading from immutable data is not impure; the function will still return the same value every time. If name were a var then that function would be impure, since something external could change name, so multiple calls to upcase() might evaluate to different values.

    (Of course it might be possible to e.g. alter name through reflection. Properly we can only talk about purity with respect to some notion of what kind of functions are allowed to call a given function, and what kind of side effects we consider to be equivalent)

    It's worth noting that your function is not pure because toUpperCase is not pure; it depends on the system's default Locale, and may produce different results on different systems (e.g. on a Turkish system, "i".toUpperCase == "İ"). You should always pass an explicit Locale, e.g. def upcase() = name.toUpperCase(Locale.ENGLISH); then the function will be pure.

    这篇关于如果它从外部读取一些数据而不是参数,它是一个纯函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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