Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 为什么这个函数中有一个非穷举模式?_Haskell - Fatal编程技术网

Haskell 为什么这个函数中有一个非穷举模式?

Haskell 为什么这个函数中有一个非穷举模式?,haskell,Haskell,在这个脚本中 permutations :: Integer -> Integer -> Integer permutations x y | x==x-(y-1) = x | (x>0) && (y>0) = permutations (x-1) y * x 我想知道为什么函数排列中有非穷举模式 请帮帮我 非常感谢你的进步 您尚未指定处理一个或两个参数均为负值的情况的逻辑。但是,您的函数将很高兴地

在这个脚本中

permutations :: Integer -> Integer -> Integer
permutations x y
            | x==x-(y-1)     = x
            | (x>0) && (y>0) = permutations (x-1) y * x
我想知道为什么函数排列中有非穷举模式

请帮帮我


非常感谢你的进步

您尚未指定处理一个或两个参数均为负值的情况的逻辑。但是,您的函数将很高兴地允许向其传递否定参数,这就是为什么会出现错误的原因。要解决此问题,您可以在末尾添加一个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"
请注意,我在第一种情况下添加了一个条件-您不应该能够计算
x
的排列,因此基本情况应该是
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]
导入数据列表(foldl')
排列::整数->整数->整数

置换x y=如果有(当两个参数中的一个为负时会发生什么?如果两个都为负怎么办?请注意
x==x-(y-1)
相当于
y==1