There are few approaches to your problem. First of all, you may use nothing
to distinguish whether a BMI
was passed to your function
function do_something(age, height; BMI = nothing)
print("hi, I am $age years old and my height is $height")
if !isnothing(BMI)
print("My BMI is $(BMI(age,height))")
end
print("bye")
end
If you are on an older version of Julia (I think 1.1 or lower) you should use BMI !== nothing
, take notice of double equal sign. There are reasons why it is better than use !=
. It may not look important in your particular case, but it is better to make good habits from the start.
But at the same time, I would recommend to use multiple dispatch, which may look excessive here, but it gives you taste and feel of Julia and also make it possible to naturally extend your initial declaration
do_bmi(bmi::Nothing, age, height) = nothing
do_bmi(bmi, age, height) = print("My BMI is $(bmi(age,height))")
function do_something(age, height; BMI = nothing)
print("hi, I am $age years old and my height is $height")
do_bmi(BMI, age, height)
print("bye")
end
For example, if you would like to give user possibilty to choose BMI
from the set of predefined functions, abbreviated by some String
, all you have to do is define this function
function do_bmi(bmi::AbstractString, age, height)
if bmi == "standard"
do_bmi((a, h) -> a^2/h, age, height)
else
println("Unknown BMI keyword $bmi")
end
end
and call your original function like this
do_something(20, 170, BMI = "standard")