繁体   English   中英

如何理解和修复“无法匹配类型”错误?

[英]How to understand and fix “Couldn't match type” errors?

我正在尝试制作一个 function ( conta conta:: Int -> Polinomio -> Int ),它给了我一个( conta np )告诉我我在p中有多少n

type Polinomio = [Monomio]
type Monomio = (Float,Int)

conta :: Int -> Polinomio -> Int
conta n [] = 0
conta n ((x,y):xs) = if n == y then x else conta xs
 Ficha2.hs:83:37: error: • Couldn't match expected type 'Int' with actual type 'Float' • In the expression: x In the expression: if n == y then x else conta xs In an equation for 'conta': conta n ((x, y): xs) = if n == y then x else conta xs Ficha2.hs:83:44: error: • Couldn't match expected type 'Int' with actual type 'Polinomio -> Int' • Probable cause: 'conta' is applied to too few arguments In the expression: conta xs In the expression: if n == y then x else conta xs In an equation for 'conta': conta n ((x, y): xs) = if n == y then x else conta xs Ficha2.hs:83:50: error: • Couldn't match expected type 'Int' with actual type '[Monomio]' • In the first argument of 'conta', namely 'xs' In the expression: conta xs In the expression: if n == y then x else conta xs

两个错误:

  1. conta xs应该是conta n xs 递归调用需要与初始调用相同类型的 arguments。
  2. conta 的类型应该是Int -> Polinomio -> Float ,而不是Int -> Polinomio -> Int 这是因为它返回元组的第一部分,即Float

阅读@Josepf Sible 的出色答案,您应该做的更正是:

type Polinomio = [Monomio]
type Monomio = (Float,Int)

conta :: Int -> Polinomio -> Float
conta n [] = 0
conta n ((x,y):xs) = if n == y then x else conta n xs

例子:

 conta 3 [(4.4,5),(5.2,3)]
=> 5.2

我们来看看错误:

 Ficha2.hs:83:37: error: • Couldn't match expected type 'Int' with actual type 'Float' • In the expression: x In the expression: if n == y then x else conta xs In an equation for 'conta': conta n ((x, y): xs) = if n == y then x else conta xs

x有问题

if n == y then x else conta xs

问题是x是(实际类型) Float ,而实际上它应该是Int 它应该是一个Int ,因为您承诺从conta返回一个Intxconta返回的值:

conta :: Int -> Polinomio -> Int

它是一个Float ,因为您使用((x, y): xs)来匹配Polinomio并最终匹配(Float, Int) 因此我们从conta的第二个参数的类型知道x是一个Float

type Polinomio = [Monomio]
type Monomio = (Float, Int)
conta :: Int -> Polinomio -> Int
conta n ((x, y) : xs) = ...

暂无
暂无

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

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