into_r
into_r

Reputation: 395

MethodError: no method matching in user defined function

in order to get started with Julia I am trying to construct a very simple function that gets me the a posterior distribution:

grid_length = 20
k_successes = 6
n_trials = 9
prior = ones(grid_length)

function plot_posterior(grid_length::Int64 , k_successes::Int64 , n_trials::Int64 , prior::Any = nothing )

# define grid, possible parameter values ( our paremeter is the probability of success vs failure)
p_grid = collect(range(0, 1, length = grid_length)) 
    
# define uninformative prior if it is not specified
    if isnothing(prior)
        prior = ones(grid_length)
    end

# compute likelihood at each value in grid
likelihood = [prob_binomial(k_successes , n_trials , prob) for prob in p_grid]
# compute product of likelihood and prior
unstd_posterior = likelihood .* prior
# standardize the posterior, so it sums to 1
posterior = unstd_posterior ./ sum(unstd_posterior) 

x = p_grid; y = posterior 
Plots.plot(x, y)
    
end

when I try

plot_posterior(grid_length=20 , k_successes=6 , n_trials=10 , prior = nothing )

I get the following error :

MethodError: no method matching plot_posterior(; grid_length=20, k_successes=6, n_trials=10, prior=nothing) Closest candidates are: plot_posterior(!Matched::Int64, !Matched::Int64, !Matched::Int64) at In[6]:9 got unsupported keyword arguments "grid_length", "k_successes", "n_trials", "prior" plot_posterior(!Matched::Int64, !Matched::Int64, !Matched::Int64, !Matched::Any) at In[6]:9 got unsupported keyword arguments "grid_length", "k_successes", "n_trials", "prior" plot_posterior(!Matched::Any, !Matched::Any, !Matched::Any) at In[3]:9 got unsupported keyword arguments "grid_length", "k_successes", "n_trials", "prior" ...

Any help on what may be happening ?

Thanks in advance

Upvotes: 3

Views: 560

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

In the signature:

function plot_posterior(grid_length::Int64,
                        k_successes::Int64,
                        n_trials::Int64,
                        prior::Any = nothing)

you define positional arguments, so a correct call to your function would be:

plot_posterior(20, 6, 10, nothing)

If you would want to use argument names in the call you need to define your arguments as keyword like this:

function plot_posterior(;grid_length::Int64,
                        k_successes::Int64,
                        n_trials::Int64,
                        prior::Any = nothing)

Note that I added ; in front of the argument list.

In general you can mix positional and keyword arguments in a single function definition, e.g.:

f(a; b) = # your definition

and now a is a positional argument and b is a keyword argument. You can read more about this in the Julia Manual here and in particular about keyword arguments here.

Upvotes: 5

Related Questions