Adding a parameter to a function - how to think about dispatch?

I’m working my way through the 2021 Computational Thinking course. In the transformations: II - Functions with parameters section

I’m not really understanding what I can do when parameterising a multiply-dispatched variant of a function.

Within Pluto I get a complaint that I’m creating multiple definitions of f. This may or may not be a Pluto problem. Anyway…

f(v) = [ v[1]+v[2] , v[1]-v[2] ]
f(α) = ((x,y),) -> [x + αy, x - αy]

I was hoping that f(3.0) would be a partial application of the α parameter and result in a single-Vector argumented function compatible with f(v). It seems like a good story :slight_smile:

Is there way of doing this - in the spirit of the two expressions above?

I don’t understand how the compiler is interpreting the parameters.

julia> f(v) = [ v[1]+v[2] , v[1]-v[2] ]
f (generic function with 1 method)

julia> f(α) = ((x,y),) -> [x + αy, x - αy]
f (generic function with 1 method)

julia> g = f(2.0)
#1 (generic function with 1 method)

julia> g((5,7),)
ERROR: UndefVarError: αy not defined
Stacktrace:
 [1] (::var"#1#2")(::Tuple{Int64, Int64})
   @ Main ./REPL[3]:1
 [2] top-level scope
   @ REPL[7]:1

julia> typeof(g)
var"#1#2"

In your example, your second line does not define another method for f, but just redefines the first one, because f(v) and f(α) are both methods with the same number of arguments of any type. You have to give more specific argument types in at least one of the two definitions, for instance:

julia> f(v) = [ v[1]+v[2] , v[1]-v[2] ]
f (generic function with 1 method)

julia> f(α::Number) = ((x,y),) -> [x + α*y, x - α*y]
f (generic function with 2 methods)

julia> g = f(2.0)
#1 (generic function with 1 method)

julia> g((5,7),)
2-element Vector{Float64}:
 19.0
 -9.0

Also, note in the error message that you got, that αy is not taken as the product of α times y, but as a single name (I’ve fixed also that in the example above).

2 Likes

Thanks so much.

In the original code in pluto, the \alpha was right next to the y, implying multiplication. Why did that work there? Actually it may just have been in markdown…

f(α) = ((x,y),) -> [x + αy, x - αy]

That line of code is not actually executed in the notebook, so I do think it’s a mistake.

1 Like

if i had looked down a few lines…

If αy were to mean multiplication, how would one go about creating a variable called αy? Any multi-character identifier would be ambiguous.

The reason 2x can be interpreted as multiplication is that it isn’t a valid variable name.

1 Like

Thanks - that’s good.
I had made up a story if \alpha had been declared as a parameter it could be flagged as a variable. But I thought that might make a cranky parser.