我已经用几个测试用例编写了此函数:
characterCounter <- function(char1, char2) {
if(is.null(char1) || is.null(char2)) {
print("Please check your character sequences!")
return()
}
if(nchar(char1, type = "chars") < nchar(char2, type = "chars") || nchar(char1, type = "chars") <= nchar(char2, type = "chars")) {
cat(sprintf("%s is smaller or smaller-equal than %s\n", char1 , char2))
return()
} else if(nchar(char1, type = "chars") > nchar(char2, type = "chars") || nchar(char1, type = "chars") >= nchar(char2, type = "chars")) {
cat(sprintf("%s is greater or greater-equal than %s\n", char1 , char2))
return()
} else if(nchar(char1, type = "chars") == nchar(char2, type = "chars")) {
cat(sprintf("%s is equal to %s\n", char1, char2))
return()
}
}
#Testcases
(characterCounter("Hello","Hell"))
(characterCounter("Wor","World"))
但是,在每种情况下我都会回来:
> (characterCounter("Hello","Hell"))
Hello is greater or greater-equal than Hell
NULL
> (characterCounter("Wor","World"))
Wor is smaller or smaller-equal than World
NULL
我不喜欢输出的内容NULL
。我为什么要把它取回来?(characterCounter(NULL,NULL))
更新
characterCounter <- function(char1, char2) {
if(is.null(char1) || is.null(char2)) {
return(cat("Please check your character sequences!"))
}
if(nchar(char1, type = "chars") < nchar(char2, type = "chars") || nchar(char1, type = "chars") <= nchar(char2, type = "chars")) {
return(cat(sprintf("%s is smaller or smaller-equal than %s\n", char1 , char2)))
} else if(nchar(char1, type = "chars") > nchar(char2, type = "chars") || nchar(char1, type = "chars") >= nchar(char2, type = "chars")) {
return(cat(sprintf("%s is greater or greater-equal than %s\n", char1 , char2)))
} else if(nchar(char1, type = "chars") == nchar(char2, type = "chars")) {
return(cat(sprintf("%s is equal to %s\n", char1, char2)))
}
}
你得到,NULL
因为那是你的回报。尝试使用invisible
:
f1 = function() {
cat('smth\n')
return()
}
f2 = function() {
cat('smth\n')
return(invisible())
}
f1()
#smth
#NULL
f2()
#smth
请注意,如果您用一组额外的括号强行输出,您仍然会得到NULL
:
(f2())
#smth
#NULL
最后,作为一般的编程笔记,我认为除单行外,非常希望return
在函数和解决方案中有一条语句,这些语句通过不返回来避免输出不是那么好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句