如何避免内容相似的链长

问题描述 投票:0回答:1

我当前正在编写R函数get_line_type(line),以输出行(字符串)的type。对于每种当前可能的类型,都有一个形式为is_TYPENAME_line(line)的函数,该函数返回一个布尔值,该值指示该行是否为该特定类型。将这些is_TYPENAME_line函数链接在一起将创建get_line_type(line)函数,当前看起来像这样

is_fish_line <- function(line) {
  return (any(grep("fish", line)))
}

is_mouse_line <- function(line) {
  return (any(grep("mouse", line)))
}

get_line_type <- function(line) {
  identified_types <- character(0)

  if(is_fish_line(line)) { identified_types[length(identified_types) + 1] <- "FISH" }
  if(is_mouse_line(line)) { identified_types[length(identified_types) + 1] <- "MOUSE" }

  if (length(identified_types) > 1) {
    stop("Matched multiple types: ", paste(identified_types, collapse = ", "), "\t", "Line: ", line)
  }

  return(if(length(identified_types) == 1) identified_types[1] else "UNKOWN")
}

此代码的工作方式如下

> get_line_type("The fish seems happy.")
[1] "FISH"
> get_line_type("A mouse is living in this house.")
[1] "MOUSE"
> get_line_type("The tiger is the king of the jungle.")
[1] "UNKOWN"
> get_line_type("The fish and the mouse are friends.")
Error in get_line_type("The fish and the mouse are friends.") : 
  Matched multiple types: FISH, MOUSE Line: The fish and the mouse are friends.

在函数内部,将创建一个列表identified_types,其中包含参数行所有已识别类型的名称。如果未找到类型,则返回UNKOWN。如果仅识别出一种类型,则返回识别出的类型。如果识别出一种以上的类型,则会发生错误(不应发生)。

[将来可能的类型列表可能会增加,我可以在链中添加另一个if语句以完成此工作,但我想知道是否有更优雅的方法,因为每个条件看起来都如此类似。

r if-statement design-patterns matching
1个回答
0
投票

我不确定这是否是您要找的东西,但这是要考虑的事项:

创建包含包含在函数中的“ TYPENAMES”的向量。然后,您可以动态构建这些功能,并将其放置在名为funcList的命名列表中。

您的get_line_type函数可以调用所有函数,并提供line作为参数。从这些函数返回TRUEFALSE时,可以轻松简化结果。

[我在评论中注意到,您可能有两个单词,两个单词之间都带有空格(例如,“产品搜索”)。在all_types中,您需要在这些词之间加下划线,以创建无空格的可用函数。另外,如果需要,可以修改identified_types以删除下划线。

all_types <- c("fish", "mouse")
funcList <- lapply(all_types, function(x) eval(parse(text = paste0('is_', x, '_line'))))
names(funcList) <- all_types

get_line_type <- function(line) {
  lst <- lapply(funcList, do.call, list(line))
  identified_types <- names(lst[unlist(lst)])
  if (length(identified_types) > 1) {
    stop("Matched multiple types: ", paste(identified_types, collapse = ", "), "\t", "Line: ", line)
  }
  return(if(length(identified_types) == 1) identified_types[1] else "UNKNOWN")
}
© www.soinside.com 2019 - 2024. All rights reserved.