gpt4 book ai didi

haskell - 无法理解编码逻辑/原理/约定 - 为什么需要 'Show a'?为什么 'Show Car"或 "Show String"不起作用?

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

下面给出的代码可以编译,ok。

data Car p q r = Car {company :: p  
, model :: q
, year ::r
} deriving (Show)


tellCar :: (Show a) => Car String String a -> String

什么基本原则/约定/逻辑可以提醒我只需要在“tellCar”中选择“Show a”,而不是任何其他选项?我在哪里可以找到资源来学习这些原则/约定/逻辑?

如果我在tellCar中错误地采用了“Show Car”,则在编译时会收到以下错误消息:

*Main> :load "/home/optimight/baby.hs"  
[1 of 1] Compiling Main ( /home/optimight/baby.hs, interpreted )

/home/optimight/baby.hs:96:18:
Expecting three more arguments to `Car'
In the type signature for `tellCar':
tellCar :: Show Car => Car String String a -> String
Failed, modules loaded: none.

如果我在tellCar中错误地使用了“Show z”,编译时会收到以下错误消息:

*Main> :load "/home/optimight/baby.hs"  
[1 of 1] Compiling Main ( /home/optimight/baby.hs, interpreted )

/home/optimight/baby.hs:96:1:
Ambiguous constraint `Show z'
At least one of the forall'd type variables mentioned by the constraint
must be reachable from the type after the '=>'
In the type signature for `tellCar':
tellCar :: Show z => Car String String a -> String
Failed, modules loaded: none.

如果我在tellCar中错误地采用了“显示字符串”,则在编译时会收到以下错误消息:

Prelude> :load "/home/optimight/baby.hs"  
[1 of 1] Compiling Main ( /home/optimight/baby.hs, interpreted )

/home/optimight/baby.hs:96:1:
Non type-variable argument in the constraint: Show String
(Use -XFlexibleContexts to permit this)
In the type signature for `tellCar':
tellCar :: Show String => Car String String a -> String
Failed, modules loaded: none.

最佳答案

tellCar :: (Show a) => Car String String a -> String

请记住这里Show a的含义是:

In the type specification that follows the =>, a should have an instance for Show.

这意味着 Car 数据构造函数的第三个参数必须是具有 Show 实例的某种类型。

指定(Show Car) => …(Show String) => …是没有意义的;这些具体类型可能有也可能没有 Show 实例(在本例中它们都有),但它并没有阐明实际类型 Car String String a -> String 任意。

指定(Show z) => … 表示:

In the type specification that follows the =>, z should have an instance for Show.

请注意,后面的类型是 Car String String a -> String,我们可以得出结论,a) z 从未被提及,所以我们可以忽略 (Show z) => …,并且 b) a 是多态的,没有约束! (即您不能依赖它拥有任何特定的类型类实例,包括 Show)

关于haskell - 无法理解编码逻辑/原理/约定 - 为什么需要 'Show a'?为什么 'Show Car"或 "Show String"不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11600254/

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