Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for optional positional arguments in the dynamic DSL. #195

Merged
merged 7 commits into from
Mar 2, 2020

Conversation

ztangent
Copy link
Member

@ztangent ztangent commented Feb 28, 2020

Currently, the built-in modeling languages and the GFI have no support for optional trailing arguments, nor for keyword arguments. This pull request provides support for optional trailing arguments for the dynamic modeling language (but not the static modeling language), enabling the following:

@gen function foo(x, y=2, (grad)(z::Float64=3.0))
    a = @trace(normal(x+y+z, 1), :a)
    b = @trace(normal(a, 1), :b)
    return (x, y, z, x+y+z)
end

foo can now be called with optional arguments omitted:

julia> foo(5, 4)
(5, 4, 3.0, 12.0)

Traces produced by generate, simulate, update, etc., have default arguments filled in as expected:

julia>  tr, w = generate(foo, (5, 4), choicemap());
julia> get_args(tr)
(5, 4, 3.0)
julia> new_tr, _, _, _ = update(foo, (1,), (UnknownChange(),) choicemap());
julia> get_args(new_tr)
(1, 2, 3.0)

Combinators also work as expected:

julia> map_foo = Map(foo);
julia> tr, w = generate(map_foo, ([1, 2, 3], [4, 5, 6]), choicemap());
julia> get_retval(tr)[3]
(3, 6, 3.0, 12.0)

We can even do optional arguments with GenerativeFunctions as default values!

@gen function outer(inner::GenerativeFunction=foo)
    @trace(inner(1), :inner)
end
julia> foo_but_with_one_less_argument = outer;
julia> foo_but_with_one_less_argument()
(1, 2, 3.0, 6.0)

Test cases are provided in test/optional_args.jl, and the docs have been updated accordingly to characterize behavior when optional arguments are omitted.

@bzinberg
Copy link
Contributor

Awesome!

Is there documentation you can update, ideally within this PR?

@ztangent
Copy link
Member Author

@bzinberg Yup, I'll do that, and add some test cases to make sure combinators etc. are working with this change!

src/dsl/static.jl Outdated Show resolved Hide resolved
@marcoct
Copy link
Collaborator

marcoct commented Mar 2, 2020

@ztangent Nice job. I just had one comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants