Skip to content

Instantly share code, notes, and snippets.

@StefanKarpinski
Last active July 19, 2019 15:10
Show Gist options
  • Save StefanKarpinski/4509b6499f0c76446a4ba4f0f7bf1354 to your computer and use it in GitHub Desktop.
Save StefanKarpinski/4509b6499f0c76446a4ba4f0f7bf1354 to your computer and use it in GitHub Desktop.
method vs lambda
f(x::Int) = "$x is an integer"
f(x::String) = "$x is a string"
g = x::Int -> "$x is an integer"
g = x::String -> "$x is a string"
julia> f(123)
"123 is an integer"
julia> f("hi")
"hi is a string"
julia> f = "oops, constant"
ERROR: invalid redefinition of constant f
Stacktrace:
[1] top-level scope at REPL[7]:1
julia> g(123)
ERROR: MethodError: no method matching (::getfield(Main, Symbol("##5#6")))(::Int64)
Closest candidates are:
#5(::String) at REPL[4]:1
Stacktrace:
[1] top-level scope at REPL[8]:1
julia> g("hi")
"hi is a string"
julia> g = "this is fine"
"this is fine"
@StefanKarpinski
Copy link
Author

Explanation:

  • f has multiple methods—it can be called on both Ints or Strings
  • f is a constant binding and cannot be reassigned
  • g is non-constant and takes on three different values:
    1. an anonymous function that can be called only on Ints
    2. an anonymous function that can be called only on Strings
    3. the string "this is fine"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment