简体   繁体   English

朱莉娅:函数的可选参数类型为Vector,但默认为null?

[英]Julia: function with optional argument of type Vector but default to null?

I have a function f(x) . 我有一个函数f(x) I would like that function to have an optional parameter of type vector. 我希望该函数具有类型为vector的可选参数。 For instance, f(x; y::Vector=[1,2,3]) . 例如, f(x; y::Vector=[1,2,3]) However, I'd like the default value to be something else (null? missing? void?) so that I can easily catch it and react to it. 但是,我希望默认值是其他值(空?缺少?无效?),以便我可以轻松地捕获它并对其作出反应。

In R, I would say function(x, y=NULL){} and then if(is.null(y)){whatever} . 在R中,我会说function(x, y=NULL){} ,然后说if(is.null(y)){whatever}

What would be the most julian way of doing something similar? 做类似事情的最朱利安方法是什么?

The pattern referenced in the comment by Engineero is cleanest, but it assumes a positional argument. Engineero的注释中引用的模式是最干净的,但它假定一个位置自变量。 If you insist on having a keyword argument (as you do in your question) to your function use: 如果您坚持要对函数使用关键字参数(如您在问题中所做的那样),请使用:

function f(x; y::Union{Vector, Nothing}=nothing)
    if y === nothing
        # do something
    else
        # do something else
    end
end

This is usually needed only if you have a lot of keyword arguments, as otherwise I would recommend defining methods with different positional parameter signatures. 通常只有在您有很多关键字参数时才需要这样做,否则我建议您定义具有不同位置参数签名的方法。

Of course it is fully OK to use this pattern with nothing also for positional arguments if you find it preferable. 当然,如果发现更可取,则完全不使用此模式nothing可以用于位置参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM