繁体   English   中英

Haskell中的“无限类型”错误,找不到错误

[英]“infinite type” error in haskell, cannot find whats wrong

我得到这个错误

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)

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

因此,GHC提出了完全错误的c类型,并感到非常困惑。

括号引起的轻微问题导致类型检查器推断出意外的类型。 首先,您的代码经过重新格式化:

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函数有可能被破坏,因为您使用的是headtail ,请考虑

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM