如果我的函数是递归的,我如何在第一次递归时运行一行?我不希望每次递归都运行该行。
答案 0 :(得分:2)
我可能会为此编写一个包装函数,所以你会得到这样的东西:
function do_stuff() {
do_stuff_only_once()
do_recursive_stuff()
}
function do_recursive_stuff() {
do_base_stuff()
do_recursive_stuff()
}
这样您就不会在每个函数调用中执行if
语句,这会稍微提高可伸缩性。
答案 1 :(得分:0)
function recursiveFunction(tempValue) {
if(tempValue==1) {
//exceute code one line code
}
// other function code here
recursiveFunction(tempValue++)
}
/*Call function */
recursiveFunction(1)
答案 2 :(得分:0)
您可以使用dbstack。如果我有如下功能
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_HAPPY_PHOTO || requestCode == REQUEST_SURPRISED_PHOTO || requestCode == REQUEST_AFRAID_PHOTO ||
requestCode == REQUEST_UPSET_PHOTO || requestCode == REQUEST_SAD_PHOTO) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
//Log.d("doing ids", "right before id");
//Log.d("doing ids", "id is " + id);
if(requestCode == REQUEST_HAPPY_PHOTO) {
//Log.d("doing ids", "in happy");
happyList.add(selectedImageUri);
}
if(requestCode == REQUEST_SURPRISED_PHOTO) {
//Log.d("doing ids", "in surprised");
surprisedList.add(selectedImageUri);
}
if(requestCode == REQUEST_AFRAID_PHOTO) {
//Log.d("doing ids", "in surprised");
afraidList.add(selectedImageUri);
}
if(requestCode == REQUEST_UPSET_PHOTO) {
//Log.d("doing ids", "in surprised");
upsetList.add(selectedImageUri);
}
if(requestCode == REQUEST_SAD_PHOTO) {
//Log.d("doing ids", "in surprised");
sadList.add(selectedImageUri);
}
}
}
}
当我调用它时,它显示我的代码深度有多少函数。问题是,如果我想在很多地方使用它,那么dbstack的长度是不够的。在这种情况下,我必须使用dbstack结构的名称字段。如果我只想要一次,它就像这样
function tmp(iter)
x = dbstack;
disp(length(x));
if iter < 10
tmp(iter+1)
end
答案 3 :(得分:0)
另一种选择是使用持久变量:
持久变量保留其对函数的多次调用的值。如果您有初始化值,这是理想的。
function tmp()
persistent already_done
if isempty(already_done)
disp('once');
already_done = true;
end