当我尝试创建类型为instance
的{{1}}时,我得到Show
使用的地方,并显示以下消息:
show
Company.hs
Ambiguous occurrence `show'
It could refer to either `Prelude.show',
imported from `Prelude' at [..]\Company.hs (and originally defined in `GHC.Show')
or `Company.show',
defined at [..]\Company.hs:29:5
PS 添加了我刚刚在Prelude中加载的所有模块。错误是module Company where
import Data.List
data Worker=Worker{
age::Int,
name::String,
title::Title,
income::Int
}
names=["age","name","title","income"]
accesors=[show . age,show . name, show . title,show .income]
data Title=Manager | Dev | Tester deriving (Show)
data Company=Company{
cname::String,
people::[Man],
yf::Int
}deriving (Show)
instance Show Man where
show w = intercalate "," (zipWith (\name acc->name++":"++acc w) names accesors)
应用于所有show
。
答案 0 :(得分:2)
编辑后:您的问题是由于缩进造成的。您需要在show w = ...
之前添加至少一个空格,否则它将成为Company模块内的顶级定义,从而导致有两个单独的show
定义,其中一个没有重载,而不是instance Show Man
定义的一部分。
在编辑之前:由于缺少部分,代码不会执行,但是添加这些缺少的部分也不会产生警告:
module Main where
import Data.List
data Title = Manager | Dev | Tester deriving (Show)
data Man = Man { _age :: Int
, _name :: String
, _title :: Title
, _income :: Int
}
instance Show Man where
show m = intercalate "," (zipWith (\name acc -> name ++ ":" ++ acc m) names accessors)
data Company = Company { _cname :: String
, _people :: [Man]
, _yf :: Int
}
instance Show Company where
show (Company cname people yf) =
intercalate "\n " $
("Company (" ++ cname ++ ", " ++ show yf ++ "):") : map show people
names :: [String]
names = ["age", "name", "title", "income"]
accessors :: [Man -> String]
accessors = [show . _age, show . _name, show . _title, show . _income]
main :: IO ()
main = do
print alice
print bob
print (Company "Alice & Bob's" [alice, bob] 1)
alice, bob :: Man
alice = Man 41 "Alice" Manager 41000
bob = Man 42 "Bob" Manager 42000
礼物:
$ ./show
age:41,name:"Alice",title:Manager,income:41000
age:42,name:"Bob",title:Manager,income:42000
Company (Alice & Bob's, 1):
age:41,name:"Alice",title:Manager,income:41000
age:42,name:"Bob",title:Manager,income:42000
尽管您可能会对deriving (Show)
感到满意。