在花时间仔细检查这段代码之前,请先阅读下面的粗体文本后的问题。如果您无法回答这个问题,我不想浪费您的时间。
好的。我在 Haskell 中创建了自己的数据类型。这是
data Dialogue= Choice String [(String, Dialogue)]
| Action String Event
-- deriving (Show)
Run Code Online (Sandbox Code Playgroud)
请注意注释掉的“导出(显示)”,这对于我下面的问题很重要。
我有一个名为对话的函数定义为
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"
Run Code Online (Sandbox Code Playgroud)
我的数据类型游戏定义为
data Game = Game Node Party [Party] | Won
deriving (Eq,Show)
Run Code Online (Sandbox Code Playgroud)
事件是一种类型,我自己定义为
type Event = Game -> Game
Run Code Online (Sandbox Code Playgroud)
现在,这就是我的问题发生的地方。当我在 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)
Run Code Online (Sandbox Code Playgroud)
在我看来,我需要包含派生(显示)以便能够将此数据类型打印到控制台。但是,当我包含deriving (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
Run Code Online (Sandbox Code Playgroud)
我花了很长时间试图找出为什么会发生这种情况。但我在网上找不到任何似乎记录这个特定问题的地方。
任何帮助都是完美的,甚至只是一个适当解释的链接。
**编辑:** 我的事件是类型同义词,因此我无法将派生显示添加到此
多谢
Event正如您所定义的,它是一个没有合理方法来显示的函数。您希望如何显示此信息?一种解决方案是import Text.Show.Functions,它有一个实例。
例如:
Prelude Text.Show.Functions> show (+ 1)
"<function>"
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是定义您自己的 show 实例:
instance Show (a -> b) where
show _ = "_"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1553 次 |
| 最近记录: |