gpt4 book ai didi

Haskell 类型推断导致错误消息指向错误的变量

转载 作者:行者123 更新时间:2023-12-05 09:01:16 26 4
gpt4 key购买 nike

在ghci中加载以下代码

{-# OPTIONS_GHC -Wall   #-}


--following gives a type error about the arg int not str
bug :: String -> Int -> Int
bug str int = num
where num = str * 10 + int

-- the following gives a type error about the arg str as expected
works :: String -> Int -> Int
works str int = str * 10 + int

出现以下错误:

:reload
[1 of 1] Compiling Main ( bugTI.hs, interpreted )

bugTI.hs:6:16: error:
• Couldn't match type ‘[Char]’ with ‘Int’
Expected: Int
Actual: String
• In the expression: num
In an equation for ‘bug’:
bug str int
= num
where
num = str * 10 + int
|
6 | bug str int = num
| ^^^

bugTI.hs:7:29: error:
• Couldn't match type ‘Int’ with ‘[Char]’
Expected: String
Actual: Int
• In the second argument of ‘(+)’, namely ‘int’
In the expression: str * 10 + int
In an equation for ‘num’: num = str * 10 + int
|
7 | where num = str * 10 + int
| ^^^

bugTI.hs:10:17: error:
• Couldn't match type ‘[Char]’ with ‘Int’
Expected: Int
Actual: String
• In the first argument of ‘(*)’, namely ‘str’
In the first argument of ‘(+)’, namely ‘str * 10’
In the expression: str * 10 + int
|
10 | works str int = str * 10 + int
| ^^^
Failed, no modules loaded.

函数错误中第 7 行的错误表明它期望 int 是一个字符串,这在算术表达式中是没有意义的。

函数中第 10 行的相应错误表示它期望 str 是一个有意义的 Int。

在我看来,第 7 行的错误充其量是误导性的,最坏的情况下(而且不太可能)是一个错误。有人可以解释为什么错误指向错误的变量吗?我想有些事情我不明白。

最佳答案

It seems to me that the error for line 7 is at best misleading, at worst (and unlikely) a bug. Can somebody explain why the error points to the wrong variable? I assume there is something I don't understand.

(*) :: Num a => a -> a -> a 没有任何“特别”之处, (+) :: Num a => a -> a -> a 等功能。这些只是在 Num 中定义的函数类型类。

您可以使其他类型成为 Num 的成员typeclass 也是如此,如果人们定义自己的类似数字的类型,这通常会发生。

因此,如果您愿意,您可以为 Num 定义一个实例对于 String类型,或一般列表。例如,您可以根据列表的长度对数字进行编码,从而推导出其算术。那看起来像:

import Data.List(genericReplicate)

instance Num [a] where
(+) = (++)

(*) = (<*)

abs = id

signum = take 1

fromInteger = (`genericReplicate` undefined)

xs - ys = drop (length ys) xs

我同意这作为 Num 的实例没有多大意义, 但它是实现这一点的可能方法之一。

Haskell 提示的是两个操作数和返回类型都需要具有相同的类型。确实,在签名中 Num a => <b>a</b> -> <b>a</b> -> <b>a</b> , a用于两个操作数和返回类型。

int类型为 Int通过类型签名,这意味着加法的两个操作数需要是 Int s,因此是 str * 10 的结果应该是 Int , 这对 10 不是问题, 但是 str 的问题.即使Num [a]会成立,这仍然意味着这会出错,因为你不能乘以 IntDouble例如,或添加 IntegerInt在一起。

关于Haskell 类型推断导致错误消息指向错误的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73680760/

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