在这个脚本中,
permutations :: Integer -> Integer -> Integer
permutations x y
| x==x-(y-1) = x
| (x>0) && (y>0) = permutations (x-1) y * x
Run Code Online (Sandbox Code Playgroud)
我想知道为什么在函数排列中存在非穷举模式.
请帮我.
非常感谢你的进步!
您尚未指定处理一个或两个参数为负的情况的逻辑.但是,你的函数会很高兴地允许将负参数传递给它,这就是你得到错误的原因.要解决此问题,您可以otherwise在最后添加一个包含所需错误处理逻辑的catch-all 语句,如下所示:
permutations :: Integer -> Integer -> Integer
permutations x y
| y == 1 || x == y = x
| (x>0) && (y>0) = permutations (x-1) y * x
| otherwise = error "invalid input"
Run Code Online (Sandbox Code Playgroud)
请注意,我在第一种情况下添加了一个条件 - 您不应该在其中计算排列x < y,因此基本情况应该是y = 1或者x == y.
给出正确答案的替代解决方案是这样的:
import Data.List(foldl')
permutations :: Integer -> Integer -> Integer
permutations x y = if any (<=0) [x,y] then 0 else foldl' (*) 1 [x+1-y..x]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |