0

我得到这个错误

Polinomios.hs:117:125:
Occurs check: cannot construct the infinite type:
  t0 = (t0, t1) -> t0
Expected type: (t0, t1)
  Actual type: ((t0, t1) -> t0, t1)
In the first argument of `(:)', namely `c'
In the expression: c : l
In the expression:
  if n == (snd $ head $ l) then
      ((k + fst $ head l), n) : (tail l)
  else
      c : l

我已经用谷歌搜索过了,应该是涉及类型错误,但我 99% 肯定没有。我知道以前有人问过这个问题,但我无法解决这个问题

adecentarPolinomio :: Polinomio -> Polinomio
adecentarPolinomio p@(Pol lista) = let f = \c@(k,n) l -> if n == (snd $ head $ l) then ((k + fst $ head l),n):(tail l) else c:l
                                   listaOrdenada = listaPol $ ordenarPolinomio p
                               in Pol (foldr f [last listaOrdenada] listaOrdenada)

使用的代码:

data Coeficiente = C Int Int

data Polinomio = Pol [(Coeficiente,Grado)]

type Grado = Int


listaPol :: Polinomio -> [(Coeficiente, Int)]
listaPol (Pol l) = l

ordenarPolinomio :: Polinomio -> Polinomio
ordenarPolinomio (Pol lista) = Pol (sortBy (compare `on` snd) lista)

instance Num Coeficiente where
(+)  (C 0 a) (C 0 b) = C 0 (a+b)
(+)  (C n a) (C m b) = C n (mod (a+b) n)
(*)  (C 0 a) (C 0 b) = C 0 (a*b)
(*)  (C n a) (C m b) = C n (mod (a*b) n)
negate       (C 0 a) = C 0 (-a)
negate       (C n a) = C n (mod (-a) n)
4

2 回答 2

4

我认为k + fst $ head l是错误的。我相信它解析为(k + fst) (head l),而我相信你的意思是k + (fst $ head l).

正因为如此,GHC 提出了完全错误的类型c,并且变得非常混乱。

于 2014-12-09T15:51:07.217 回答
3

括号的小问题导致类型检查器推断出意外的类型。首先,您的代码有点重新格式化:

adecentarPolinomio :: Polinomio -> Polinomio
adecentarPolinomio p@(Pol lista) =
    let f c@(k,n) l =
            if n == (snd $ head $ l)
                then ((k + fst $ head l), n) : tail l
                else c : l
        listaOrdenada = listaPol $ ordenarPolinomio p
    in Pol (foldr f [last listaOrdenada] listaOrdenada)

像这样,我几乎可以立即发现错误,即你有(k + fst $ head l)你可能想要的地方k + fst (head l)。一旦我修复了您的代码已编译。

我想指出,您的f函数有可能会中断,因为您正在使用headand tail,相反,请考虑

adecentarPolinomio :: Polinomio -> Polinomio
adecentarPolinomio p@(Pol lista) =
    let f c@(k,n) l@((k', n'):xs) =
            if n == n'
                then ((k + k'), n) : xs
                else c : l
        f c [] = [c]
        listaOrdenada = listaPol $ ordenarPolinomio p
    in Pol (foldr f [last listaOrdenada] listaOrdenada)

现在该函数将处理空列表,您可以避免使用fstsndheadtail

于 2014-12-09T15:51:45.883 回答