首页 文章

为什么这个函数中有非详尽的模式?

提问于
浏览
2

在这个脚本中,

permutations :: Integer -> Integer -> Integer
permutations x y
            | x==x-(y-1)     = x
            | (x>0) && (y>0) = permutations (x-1) y * x

我想知道为什么在函数排列中存在非穷举模式 .

请帮我 .

非常感谢你的进步!

1 回答

  • 5

    您尚未指定处理一个或两个参数为负的情况的逻辑 . 但是,你的函数会很高兴地允许将负参数传递给它,这就是你得到错误的原因 . 要解决此问题,您可以在最后添加一个包含所需错误处理逻辑的catch-all otherwise 语句,如下所示:

    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"
    

    请注意,我在第一种情况下添加了一个条件 - 您不应该计算 x < y 所在的排列,因此基本情况应该是 y = 1x == y .

    Demo

    给出正确答案的替代解决方案是这样的:

    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]
    

相关问题