Julia语言有多少种定义函数的方法?有点多!信息量有点大,你们忍一下

普通

function name(a, b)
  a + b
  # you and optionally write `return a + b` instead 
  # but Julia returns the last value by default
end

一行

name(a,b) = a + b

names(a, b)= begin
  # some other code
  a + b
end

匿名

function(a, b)
  a+b
end

name3 = function(a,b)
  a+b
end

(a,b) -> a+b

name2 = (a,b) -> a+

macro defining_function(fnname)
    :(
        function $fnname(a, b)
          a + b
        end     
     ) 
end  
@defining_function name4

函数工厂

function fn_generator(c)
  function (a, b)
     a + b + c
  end
end

fn = fn_generator(1)
fn(2, 3) # what does this return?

这个方法不会增加一个name的函数

function fn_generator2()
  function name(a,b)
    a*b
  end
end
fn_generator2()

神马?

a*b = a+b
2*3 # == 5

Functor

function (x::Int)(y)
  x+y
end
x=2
x(3) # returns 5

无处不在

function fn_generator()
    if true
        f() = 0
    else
        f(x, y) = x+y
    end
end
name6 = fn_generator()
name6(1,2) # == 3 为什么?

Iterable

name7 = (a + b for a in 1:2, b in 3:4).f
names7((1, 2)) # gives 3

有始有终

name8 = begin
  x
  y=2
end -> x + y
name8(1) # gives 3
name8(2; y=3) # gives 5

语法糖

map(x) do x1
   2x1
end

上面跟这个是一样的

x = 1:3
map(x1->2x1, x)
12 个赞