更改变量类型以匹配预期类型

Change variable type to match the expected type

在下面的代码中,我得到了错误

Couldn't match type 'Integer' with 'Int'
Expected type :[(Test, [Test])]
Actual type : [(Integer, [Integer])]

执行时

testFunc test

使用以下声明

type TestType = Int
a = [(1,[2,3])]

testFunc :: [(TestType ,[TestType])] -> TestType 
testFunc ((a,(b:c)):d) = a

如何声明我的列表 a 以便它匹配 testFunc 的类型?

有没有办法在不修改 type Test = Inta 的声明的情况下修复错误?

How do I declare my list 'test' so that it matches the type of testFunc?

嗯,通过将其声明为类型。

a :: [(TestType, [TestType])]
a = [(1,[2,3])]

一般来说,您应该始终为这样的顶级定义提供明确的类型签名。如果没有这样的签名,编译器会为你挑选一个。通常 Haskell 会尝试尽可能选择最通用的可用类型;在这种情况下是

a :: (Num a, Num b) => [(a, [b])]

...这将包括 [(Int, [Int])][(Integer, [Integer])]。但是,monomorphism restriction默认限制了类型,排除了这种多态性。所以GHC必须选择一个版本,默认的是Integer,而不是Int

同样,正确的解决方案是提供显式签名。但是,您也可以关闭单态限制:

{-# LANGUAGE NoMonomorphismRestriction #-}

type TestType = Int
a = [(1,[2,3])]

testFunc :: [(TestType ,[TestType])] -> TestType 
testFunc ((x,(y:z)):w) = x

main :: IO ()
main = print $ testFunc a