【问题标题】:missing x with no default. Calling functions within functions in R缺少 x 没有默认值。在 R 中的函数内调用函数
【发布时间】:2020-03-31 02:19:53
【问题描述】:

我正在编写代码来解决数独难题,使用从 YouTube 找到的 video 已通过 Python 编写了相同的算法。这段代码需要三个函数来

  1. 找一个空方格。
  2. 在空方格中插入一个数字。
  3. 测试这个数字是否有效解谜。

这是对求解器使用回溯算法。

我在一起调用函数时遇到问题,出现错误:

Error in free_squ(x) : argument "x" is missing, with no default
In addition: Warning message:
In if (empty_sq == FALSE) { :
the condition has length > 1 and only the first element will be used
Called from: free_squ(x)

这很令人困惑,因为我只有在运行此代码时才会得到它。所以我可以编写其他函数来调用各个函数来分析插入到上层函数中的参数:

function1(argument){
   function2(argument){
     function3(argument){
        ***DO STUFF***}}}

为什么下面的代码主函数中的函数不能识别参数?

sudoku_solve <- function(x){

  empty_sq <- free_squ(x) # Define a new object to give coordinates of empty square

  if(empty_sq == FALSE){ # If no empty square can be found

    return(x) # Return the matrix

  } else{

    empty_sq <- empty_sq  # Pointless line kept for clarity

  }
  for(i in c(1:9)){ # Integers to insert into the found empty square

    if(valid(x, i, empty_sq) == TRUE){ # can the intiger be placed in this square?

      x[empty_sq[1], empty_sq[2]] = i # if i valid, insert into empty square
    } 


    if(sudoku_solve()){ # are all i's valid?

      return(TRUE) # All i's valid

    } else{

      x[empty_sq[1], empty_sq[2]] = 0 # reset the initial try and try again with another
    }
}
  return(FALSE)
  }

我已将数独游戏命名为“puzzle”,并通过以下方式调用该函数:

sudoku_solve(puzzle)

【问题讨论】:

  • 那么,你的“谜题”论点是什么样的?
  • 这是一个 9 x 9 矩阵

标签: r function arguments sudoku


【解决方案1】:

我认为在下面的语句中,您没有将任何值传递给函数,并且 x 也没有默认值。

if(sudoku_solve()){ # are all i's valid?
    return(TRUE) # All i's valid
}

因此,虽然最初传递了参数,但在循环之后再次调用该函数时,它会在没有参数的情况下调用。所以你在 sudoku_solve() 中传递给 free_sq(x),它给出了一个错误。

empty_sq <- free_squ(x)

确保您将值传递给 sudoku_solve 或在 sudoku_solve 或 free_squ 类/函数中设置 x wither 的默认值。

【讨论】:

  • 你好,是的,我试过了。当我在函数运行之前定义 x 或将其替换为 'puzzle' 时,它仍然说它未定义。此外,当我使用 if(sudoku_solve(x){ 它会导致无限循环
  • 'Error: C stack usage 7970320 is too close to the limit'是我通过if(sudoku_solve(x)时得到的错误
  • @James.H 你的问题得到了答案。你应该投赞成票。如果您想进一步努力,您应该阅读How to Ask 并发布minimal reproducible example
  • @42 我什至在提出问题之前就尝试了他的建议,所以我不认为这是在回答我的问题,因为它只会导致更多问题。
猜你喜欢
  • 2021-09-17
  • 2020-01-14
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多