官术网_书友最值得收藏!

Pure function

The definition of pure function says that if the return value of a function is completely dependent on its arguments/parameters, then this function may be referred to as a pure function. So, if we declare a function as fun func1(x:Int):Int, then its return value will be strictly dependent on its argument x; say, if you call func1 with a value of 3 twice, then, for both the times, its return value will be the same. A pure function can be a lambda or a named function as well. In the previous example, the first lambda expression was a pure function but not the second one, as for the second one, its return value can be different at different times with the same value passed to it. Let's look at the following example to understand it better:

    fun square(n:Int):Int {//(1) 
      return n*n 
    } 
 
    fun main(args: Array<String>) { 
      println("named pure func square = ${square(3)}") 
      val qube = {n:Int -> n*n*n}//(2) 
      println("lambda pure func qube = ${qube(3)}") 
    } 

Both the functions, (1) and (2), here are pure functions–one is named, while the other is lambda. If you pass the value 3 to any of the functions n times, their return value will be the same for each time. Pure functions don't have side effects.

Side effects: A function or expression is said to have a side effect if it modifies some state outside its scope or has an observable interaction with its calling functions or the outside world besides returning a value.
Source–Wikipedia https://en.wikipedia.org/wiki/Side_effect_(computer_science).

It is to note that, as we said earlier, pure functions have nothing to do with lambda expressions, their definitions are completely different.

The following is the output:

named pure func square = 9
lambda pure func qube = 27 
主站蜘蛛池模板: 原阳县| 怀宁县| 申扎县| 娄底市| 永年县| 永胜县| 铜陵市| 开江县| SHOW| 葫芦岛市| 类乌齐县| 额尔古纳市| 呼和浩特市| 富锦市| 乡城县| 喀什市| 石柱| 仙居县| 锦州市| 桃园县| 阿合奇县| 托克逊县| 贺兰县| 阿合奇县| 伊吾县| 九龙坡区| 惠东县| 丰镇市| 绵竹市| 肇庆市| 慈利县| 新疆| 梅河口市| 林口县| 阿克苏市| 湘乡市| 佛学| 郧西县| 青冈县| 元阳县| 莲花县|