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

Anonymous functions

The function f(x, y) at the end of the Defining functions section can also be written with no name, as an anonymous function: (x, y) -> x^3 - y + x * y. We can, however, bind it to a name, such as f = (x, y) -> x^3 - y + x * y, and then call it, for example, as f(3, 2). Anonymous functions are also often written using the following syntax (note the space before (x)):

  function (x) 
      x + 2 
  end 
(anonymous function) 
julia> ans(3) 
5 

Often, they are also written with a lambda expression as (x) -> x + 2. Before the stab character (->) are the arguments, and after the stab character we have the return value. This can be shortened to x -> x + 2. A function without arguments would be written as () -> println("hello, Julia").

Here is an anonymous function taking three arguments: (x, y, z) -> 3x + 2y - z. When the performance is important, try to use named functions instead, because calling anonymous functions involves a huge overhead. Anonymous functions are mostly used when passing a function as an argument to another function, which is precisely what we will discuss in the next section.

主站蜘蛛池模板: 临潭县| 吉林市| 贡山| 洛阳市| 鸡东县| 磐安县| 宁海县| 龙陵县| 蓝田县| 连州市| 鲁甸县| 怀远县| 蓬溪县| 吕梁市| 天等县| 延长县| 静海县| 辉县市| 江达县| 呼图壁县| 潜江市| 微博| 安平县| 盘山县| 武乡县| 霍城县| 明水县| 马公市| 宿州市| 江山市| 怀仁县| 临潭县| 成武县| 虞城县| 铜鼓县| 平乐县| 高淳县| 哈巴河县| 广安市| 浦县| 清原|