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

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.

主站蜘蛛池模板: 仪陇县| 延吉市| 深圳市| 承德市| 正镶白旗| 化州市| 赞皇县| 山阴县| 禹州市| 枣阳市| 商南县| 马关县| 库尔勒市| 北宁市| 香港 | 嫩江县| 洞口县| 江口县| 苍南县| 临潭县| 汝州市| 祁连县| 常德市| 海林市| 永安市| 通州区| 资溪县| 民丰县| 叙永县| 吉隆县| 汉沽区| 肇州县| 陇南市| 洛扎县| 寿阳县| 西峡县| 汶上县| 那曲县| 天峻县| 南岸区| 高碑店市|