gpt4 book ai didi

haskell - 奇怪的 Haskell 类型错误仅在使用 assertEqual 时发生

转载 作者:行者123 更新时间:2023-12-02 02:50:49 25 4
gpt4 key购买 nike

此代码将正确编译:

import Text.Printf
import Test.HUnit
doubleMe x = x + x
doubleUs x y = doubleMe x + doubleMe y
doubleSmallNumber x = if x > 100 then x else x*2
doubleSmallNumber' x = if x > 100 then x else x*2 + 1
conanO'Brien = "It's a-me, Conan O'Brien!"
main = do
runTestTT $ TestList [TestCase $ ae 4 $ doubleMe 2,
TestCase $ ae 10 $ doubleUs 2 3,
TestCase $ ae 4 $ doubleSmallNumber 2,
TestCase $ ae 1000 $ doubleSmallNumber' 1000,
TestCase $ assertEqual "" "It's a-me, Conan O'Brien!" conanO'Brien]
where ae = assertEqual ""

输出是:
$ clear && ghc baby.hs && ./baby     
[1 of 1] Compiling Main ( baby.hs, baby.o )
Linking baby ...
ld: warning: could not create compact unwind for .LFB3: non-standard register 5 being saved in prolog
Cases: 5 Tried: 5 Errors: 0 Failures: 0

当我将代码更改为:
import Text.Printf
import Test.HUnit
doubleMe x = x + x
doubleUs x y = doubleMe x + doubleMe y
doubleSmallNumber x = if x > 100 then x else x*2
doubleSmallNumber' x = if x > 100 then x else x*2 + 1
conanO'Brien = "It's a-me, Conan O'Brien!"
main = do
runTestTT $ TestList [TestCase $ ae 4 $ doubleMe 2,
TestCase $ ae 10 $ doubleUs 2 3,
TestCase $ ae 4 $ doubleSmallNumber 2,
TestCase $ ae 1000 $ doubleSmallNumber' 1000,
TestCase $ ae "It's a-me, Conan O'Brien!" conanO'Brien]
where ae = assertEqual ""

我得到:
[1 of 1] Compiling Main             ( baby.hs, baby.o )

baby.hs:12:65:
No instance for (Num [Char])
arising from the literal `1000'
Possible fix: add an instance declaration for (Num [Char])
In the first argument of `doubleSmallNumber'', namely `1000'
In the second argument of `($)', namely `doubleSmallNumber' 1000'
In the second argument of `($)', namely
`ae 1000 $ doubleSmallNumber' 1000'

我不明白为什么。

也有人对修复 ld 警告有任何想法:
ld: warning: could not create compact unwind for .LFB3: non-standard register 5 being saved in prolog

最佳答案

这是单态限制的一个例子。 ae “看起来像一个值”(没有参数)并且没有显式类型,因此编译器不会为其推断多态类型。

在第一个示例中,它的类型为 Int -> Int -> Assertion (我认为)。

第二,来自ae "It's a-me, Conan O'Brien!" conanO'Brien它的类型为 String -> String -> Assertion .请记住,整数文字的类型实际上是 Num a => a , 和 1000获取类型 String来自 ae , 所以编译器需要一个实例 Num String .

已编辑:这可以通过给出明确的类型注释来解决:where ae :: (Show a, Eq a) => a -> a -> Assertion = assertEqual "" .或者通过在定义中添加参数(eta-expanding):where ae x y = assertEqual "" x y .

关于haskell - 奇怪的 Haskell 类型错误仅在使用 assertEqual 时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7058716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com