(Num (Int -> Int)) 没有因使用句法否定而产生的实例
No instance for (Num (Int -> Int)) arising from a use of syntactic negation
我已将以下 Haskell 代码写入 return [[Int]]
的主要和次要对角线
getDiagonal' :: [[Int]] -> Int -> (Int -> Int) -> [Int]
getDiagonal' [] _ _ = []
getDiagonal' (x:xs) i fn = i' : getDiagonal' xs (fn i) fn
where i' = head $ drop i x
getPrimaryDiagonal :: [[Int]] -> [Int]
getPrimaryDiagonal x = getDiagonal' x 0 (+1)
getSecondaryDiagonal :: [[Int]] -> [Int]
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) (+(-1))
然而,我本以为最后一行可能是下面的,使用 (-)
与 (+)
相同的方式
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) (-1)
但是,这不起作用,当我这样做时,我得到了
Main.hs:27:59: error:
• No instance for (Num (Int -> Int))
arising from a use of syntactic negation
(maybe you haven't applied a function to enough arguments?)
• In the third argument of ‘getDiagonal'’, namely ‘(- 1)’
In the expression: getDiagonal' x ((length x) - 1) (- 1)
In an equation for ‘getSecondaryDiagonal’:
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) (- 1)
为什么 (-)
会产生该错误?
(-1)
被解释为 负数 ,据我所知,它是 non-binary 运算符的唯一例外. (-1)
因此不是减一的函数。
您可以为此使用 subtract :: Num a => a -> a -> a
:
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) <b>(subtract 1)</b>
或者您可以使用 flip :: (a -> b -> c) -> b -> a -> c
,这就是 subtract
的实现方式:
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) <b>(flip (-) 1)</b>
我已将以下 Haskell 代码写入 return [[Int]]
的主要和次要对角线getDiagonal' :: [[Int]] -> Int -> (Int -> Int) -> [Int]
getDiagonal' [] _ _ = []
getDiagonal' (x:xs) i fn = i' : getDiagonal' xs (fn i) fn
where i' = head $ drop i x
getPrimaryDiagonal :: [[Int]] -> [Int]
getPrimaryDiagonal x = getDiagonal' x 0 (+1)
getSecondaryDiagonal :: [[Int]] -> [Int]
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) (+(-1))
然而,我本以为最后一行可能是下面的,使用 (-)
与 (+)
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) (-1)
但是,这不起作用,当我这样做时,我得到了
Main.hs:27:59: error:
• No instance for (Num (Int -> Int))
arising from a use of syntactic negation
(maybe you haven't applied a function to enough arguments?)
• In the third argument of ‘getDiagonal'’, namely ‘(- 1)’
In the expression: getDiagonal' x ((length x) - 1) (- 1)
In an equation for ‘getSecondaryDiagonal’:
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) (- 1)
为什么 (-)
会产生该错误?
(-1)
被解释为 负数 ,据我所知,它是 non-binary 运算符的唯一例外. (-1)
因此不是减一的函数。
您可以为此使用 subtract :: Num a => a -> a -> a
:
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) <b>(subtract 1)</b>
或者您可以使用 flip :: (a -> b -> c) -> b -> a -> c
,这就是 subtract
的实现方式:
getSecondaryDiagonal x = getDiagonal' x ((length x) - 1) <b>(flip (-) 1)</b>