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

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.

主站蜘蛛池模板: 渭源县| 湖南省| 浏阳市| 邓州市| 中牟县| 垫江县| 蓬溪县| 即墨市| 普兰县| 江北区| 阜新市| 高雄县| 于都县| 于田县| 西充县| 东海县| 三都| 靖边县| 赤城县| 剑阁县| 舒城县| 揭东县| 渝中区| 甘孜县| 昌平区| 务川| 威远县| 论坛| 广宁县| 江门市| 南召县| 革吉县| 呼和浩特市| 馆陶县| 井研县| 达拉特旗| 卢龙县| 昌黎县| 寿阳县| 邵阳市| 石渠县|