我正在尝试编写一个函数来确定正整数列表是 a) 递增还是递减以及 b) 连续数字之间的绝对差至少为 1 且小于 3。
这是我的尝试:
isSafe :: [Int] -> Int -> Bool -> Bool
isSafe [x] _ _ = True
isSafe (x:xs) 0 isIncreasing = isSafe xs x isIncreasing
isSafe (x:xs) prev True = (x-prev >= 1) and (x-prev < 3) and isSafe xs x True
isSafe (x:xs) prev False = (x-prev <= -1) and (x-prev > -3) and (isSafe xs x False)
第二个参数是前一个元素,第三个参数是列表是否递增。
我收到此错误:
example.hs:23:28: error:
• Couldn't match expected type ‘(t2 Bool -> Bool)
-> Bool -> (t3 Bool -> Bool) -> Bool -> Bool’
with actual type ‘Bool’
• The function ‘(<=)’ is applied to six value arguments,
but its type ‘Int -> Int -> Bool’ has only two
In the expression:
(x - prev <= - 1) and (x - prev > - 3) and (isSafe xs x False)
In an equation for ‘isSafe’:
isSafe (x : xs) prev False
= (x - prev <= - 1) and (x - prev > - 3) and (isSafe xs x False)
|
23 | isSafe (x:xs) prev False = (x-prev <= -1) and (x-prev > -3) and (isSafe xs x False)
有人可以帮我理解为什么吗<= is applied to 6 values?
谢谢!
and :: Foldable f => f Bool -> Bool
函数[Hackage]需要一个Foldable
的Bool
,例如一个列表,而不是两个Bool
。
(&&) :: Bool -> Bool -> Bool
函数 [Hackage] 代替:
isSafe :: [Int] -> Int -> Bool -> Bool
isSafe [] _ _ = …
isSafe [x] _ _ = True
isSafe (x : xs) 0 isIncreasing = isSafe xs x isIncreasing
isSafe (x : xs) prev True = (x - prev >= 1) && (x - prev < 3) && isSafe xs x True
isSafe (x : xs) prev False = (x - prev <= -1) && (x - prev > -3) && (isSafe xs x False)
您可能还应该为空列表实现一个基本情况。