无法在Haskell中打印自己的数据类型
请先阅读我下面的问题,在粗体文本之后,然后再仔细阅读此代码。如果你不能回答这个问题,我不想浪费你的时间。 好的。我在Haskell中创建了自己的数据类型。是的无法在Haskell中打印自己的数据类型,haskell,Haskell,请先阅读我下面的问题,在粗体文本之后,然后再仔细阅读此代码。如果你不能回答这个问题,我不想浪费你的时间。 好的。我在Haskell中创建了自己的数据类型。是的 data Dialogue= Choice String [(String, Dialogue)] | Action String Event -- deriving (Show) 请注意注释掉的“派生(显示)”,这对于我下面的问题很重要 我有一个名为dialogue的函数,定义为 dialogue:: G
data Dialogue= Choice String [(String, Dialogue)]
| Action String Event
-- deriving (Show)
请注意注释掉的“派生(显示)”,这对于我下面的问题很重要
我有一个名为dialogue的函数,定义为
dialogue:: Game -> Dialogue -> IO Game
dialogue (Game n p ps) (Action s e) = do
putStrLn s
return (e (Game n p ps))
dialogue (Game n p ps) (Choice s xs) = do
putStrLn s
let ys = [ fst a | a <- xs ]
let i = [1..length ys]
putStrLn (enumerate 1 ys)
str <- getLine
if str `elem` exitWords
then do
return (Game n p ps)
else do
let c = read str::Int
if c `elem` i
then do
let ds = [ snd b | b <- xs ]
let d = ds !! c
putStrLn $ show d
return (Game n p ps)
else do
error "error"
data Game = Game Node Party [Party] | Won
deriving (Eq,Show)
事件是一种类型,我自己定义为
type Event = Game -> Game
现在,这就是我的问题所在。当我在cmd中加载此文件时,我的数据类型对话框中包含了而不是派生(显示),我得到以下错误:
* No instance for (Show Dialogue) arising from a use of `show'
* In the second argument of `($)', namely `(show d)'
In a stmt of a 'do' block: putStrLn $ (show d)
In the expression:
do let ds = ...
let d = ds !! c
putStrLn $ (show d)
return (Game n p ps)
|
120 | putStrLn $ (show d)
在我看来,我需要包含派生(Show),以便能够将此数据类型打印到控制台。但是,当我包含派生(Show)时,会出现以下错误:
* No instance for (Show Event)
arising from the second field of `Action' (type `Event')
(maybe you haven't applied a function to enough arguments?)
Possible fix:
use a standalone 'deriving instance' declaration,
so you can specify the instance context yourself
* When deriving the instance for (Show Dialogue)
|
85 | deriving Show
我花了相当长的时间试图找出为什么会发生这种情况。但我在网上找不到任何地方可以证明这个问题
任何帮助都是完美的,甚至只是一个适当解释的链接
**编辑:*“我的事件”是一个类型同义词,因此我无法将派生显示添加到此
非常感谢
事件
正如您所定义的,它是一个没有合理方法显示的函数。您希望如何显示此信息?一种解决方案是导入Text.Show.Functions,它有一个实例
例如:
Prelude Text.Show.Functions> show (+ 1)
"<function>"
当编译器试图为对话
派生显示
时,它必须在操作
变量中显示一个事件
,但它不能-事件
是一个函数,函数不会自动派生显示
实例
您必须手动执行显示事件
或显示对话
。实现显示对话的一种方法是:
instance Show Dialogue where
show (Choice s ds) = " " `intercalate` ["Choice", show s, show ds]
show (Action s e) = " " `intercalate` ["Action", show s]
Event
必须有一个Show
实例,才能自动派生Show
。这可能意味着将deriving Show
添加到Event
定义中。他的Event
类型是别名,不能包含派生子句。它也是一个函数,因此自动派生无法工作。您希望如何打印事件
?功能一般不能打印。也许您可以定义自己的自定义实例显示对话框
,而无需依赖显示事件
,例如,通过将其显示为某个通用字符串“”。您还可以使用UNWORD
而不是插入
。
type Event = Game -> Game
data Dialogue= Choice String [(String, Dialogue)]
| Action String Event
-- deriving (Show)
instance Show Dialogue where
show (Choice s ds) = " " `intercalate` ["Choice", show s, show ds]
show (Action s e) = " " `intercalate` ["Action", show s]