Jac*_*kOA 1 haskell pattern-matching guard-clause
我正在编写一个函数,该函数接受列表输入、创建子列表并检索输出到新列表中的 n 个元素。我正在根据输入的值编写防护,但我不断收到错误“模式不匹配:( : )_”。
\n有人确定这个问题吗?
\nnKsets :: [Int] -> Int -> [[Int]]\nnKsets [] _ = error "Empty list should not be given as input"\nnKsets l n\n | n <= 0 = []\n | n > 0 = ...\nRun Code Online (Sandbox Code Playgroud)\n我收到的错误是:
\nPattern match(es) are non-exhaustive\nIn an equation for \xe2\x80\x98nKsets\xe2\x80\x99: Patterns not matched: (_:_) _\nRun Code Online (Sandbox Code Playgroud)\n
详尽匹配器不知道 的所有值都n大于 0 或不大于 0,因此它假设您的第二个定义并不详尽。使用otherwise而不是n > 0保证守卫成功。
nKsets :: [Int] -> Int -> [[Int]]
nKsets [] _ = error "Empty list should not be given as input"
nKsets l n
| n <= 0 = []
| otherwise = ...
Run Code Online (Sandbox Code Playgroud)
您还可以使用第三个定义,而不是第二个定义上的两个防护:
nKsets :: [Int] -> Int -> [[Int]]
nKsets [] _ = error "Empty list should not be given as input"
nKsets l n | n <= 0 = []
nKsets l n = ...
Run Code Online (Sandbox Code Playgroud)