All ways to define functions in Julia?

Finally published this as an article after much procrastination

6 Likes

In the example a*b=a+b, do you want to say that 2*3 gives 5, not 6?

1 Like

Yeah. I do. Thanks

Forgot about this syntactic sugar

fn(params....) do a, b
   a  + b
end

This is defining an anonymous function (a,b)->a+b can calling it like this

fn((a,b)->a+b, params...)

which leads us to

julia> f = identity() do x
           x^2
       end
#1 (generic function with 1 method)

julia> f(3)
9
6 Likes

Probably the most complete list of possible function definitions should be in https://github.com/invenia/ExprTools.jl/blob/master/test/function.jl I mean, it’s one of the major features of ExprTools.jl, that it can work with all functions definitions.

2 Likes

For those who aren’t familiar: Tropical geometry - Wikipedia

4 Likes

Why is that a bad use of 'functor" It reminds me a lot more of the Ocaml-interpretation than the Haskell interpretation.

Not sure if it’s a bad use. Not sure where the name originated but in math functor means something different.

Found this entertaining:

julia> (x::Int)(y) = x+y; (x::Int)(;y) = x-y;

julia> (2)(4)
8

julia> (x=2)(4)
6

julia> (x=2)(y=4)
-2
6 Likes

A couple more for fun:

julia> function fib end
fib (generic function with 0 methods)

julia> Base.getindex(f::typeof(fib), n) = n ≤ 1 ? n : f[n-1]+f[n-2]

julia> [fib[n] for n = 0:7]
8-element Vector{Int64}:
  0
  1
  1
  2
  3
  5
  8
 13

julia> Base.getproperty(::typeof(cos), θ) = cos(θ)

julia> cos.:3.14
-0.9999987317275395
4 Likes

This kind of fib recursion doesn’t work in v1.5.4