Last active
August 29, 2015 14:01
-
-
Save sunetos/0714ae73647160d76aae to your computer and use it in GitHub Desktop.
Julia macro for typed optional function arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Mark a function argument of any type as optional by generating a Union. | |
# If a default value is not defined, it assumes "nothing". | |
# | |
# Examples: | |
# function(x::Int, @maybe y::MyType) | |
# function(x::Int, @maybe y::MyType=someval) | |
macro maybe(argexpr) | |
default = :nothing | |
if argexpr.head == :(=) | |
argexpr, default = argexpr.args | |
end | |
@assert (argexpr.head == :(::)) "@maybe is for typed function arguments." | |
name, ptype = argexpr.args | |
deftype = typeof(eval(default)) | |
Expr(:kw, :($name::Union($deftype, $ptype)), default) | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Base.Test | |
require("maybe.jl") | |
type TestType | |
name::String | |
end | |
# Mostly just make sure these actually parse. | |
function test_maybe1(x::Int, @maybe tt::TestType) | |
return 1 | |
end | |
function test_maybe2(x::Int, @maybe tt::TestType=nothing) | |
return 2 | |
end | |
function test_maybe3(x::Int, @maybe tt::TestType=TestType("foo")) | |
return 3 | |
end | |
function test_maybe4(@maybe x::Vector{Int}) | |
return 4 | |
end | |
incrme = 0 | |
test_maybe_expr(@maybe x::Int=incrme) = x | |
@test length(methods(test_maybe1)) == 2 | |
@test length(methods(test_maybe2)) == 2 | |
@test length(methods(test_maybe3)) == 2 | |
@test length(methods(test_maybe4)) == 2 | |
@test test_maybe1(0, TestType("")) == 1 | |
@test test_maybe1(0) == 1 | |
@test test_maybe2(0, TestType("")) == 2 | |
@test test_maybe2(0) == 2 | |
@test test_maybe3(0, TestType("")) == 3 | |
@test test_maybe3(0) == 3 | |
@test test_maybe4([0]) == 4 | |
@test test_maybe4() == 4 | |
@test test_maybe_expr() == 0 | |
incrme = incrme + 1 | |
@test test_maybe_expr() == 1 | |
incrme = incrme + 1 | |
@test test_maybe_expr() == 2 | |
@test test_maybe_expr(0) == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment