3

PhisicalCell データ型の単純な show インスタンスを手動で作成すると、プログラムがすべてのスペースを消費します。彼自身のバージョンの Show を導出するとき、これは起こりません。なんで?

ここに私が書いているコードの簡素化されたバージョンがあります:

import Data.Array

type Dimensions = (Int, Int)
type Position = (Int, Int)
data PipeType = Vertical | Horizontal | UpLeft | UpRight | DownLeft | DownRight deriving (Show)

data PhisicalCell = AirCell
                  | PipeCell PipeType
                  | DeathCell
                  | RecipientCell Object
                  -- deriving (Show) SEE THE PROBLEM BELOW  

data Object = Pipe { pipeType :: PipeType  -- tipo di tubo
                   , position :: Position  -- posizione del tubo
                   , movable  :: Bool      -- se posso muoverlo
                   }
            | Bowl { position   :: Position                 -- posizione dell'angolo in alto a sinistra
                   , dimensions :: Dimensions               -- dimensioni (orizzontale, verticale)
                   , waterMax   :: Int                      -- quanta acqua puo' contenere al massimo
                   , waterStart :: Int                      -- con quanta acqua parte 
                   , hatch      :: Maybe Position           -- un eventuale casella di sbocco
                   , sourceIn   :: [Position]               -- posti da cui l'acqua entra
                   , movable    :: Bool                     -- se posso muoverlo
                   }
            | Death
            deriving (Show)

data Level = Level Dimensions [Object]
type LevelTable = Array Dimensions PhisicalCell

-- HERE IS THE PROBLEM -- 
instance Show PhisicalCell where
show AirCell = " "
show (PipeCell _) = "P"
show DeathCell = "X"
show (RecipientCell _) = "U"

both :: (a -> b) -> (a,a) -> (b,b)
both f (a,b) = (f a, f b)

levelTable :: Level -> LevelTable
levelTable (Level dim _) = initial
  where initial = array ((0,0), both (+1) dim) $
                    [((x,y), AirCell) | x <- [1..fst dim], y <- [1..snd dim] ]
                    ++ [((x,y), DeathCell) | x <- [0..fst dim + 1], y <- [0, snd dim + 1]]
                    ++ [((x,y), DeathCell) | x <- [0, fst dim + 1], y <- [0..snd dim + 1]]

main = print $ levelTable (Level (8,12) []) 
4

2 に答える 2

7

Show型クラスには、相互に参照するデフォルトの実装があります。

class  Show a  where
    -- | Convert a value to a readable 'String'.
    --
    -- 'showsPrec' should satisfy the law
    -- ...
    ...
    showsPrec _ x s = show x ++ s
    show x          = shows x ""
    showList ls   s = showList__ shows ls s

...

shows           :: (Show a) => a -> ShowS
shows           =  showsPrec 0

したがってShow、メソッドを定義せずにインスタンスを宣言すると

instance Show where

nextNewFunction :: Bla
...

GHC はすべてのデフォルトのものを問題なくコンパイルするので、エラーは発生しません。ただし、それらのいずれかを使用しようとするとすぐに、... と同じくらい致命的なループに閉じ込められObjects、相互再帰により最終的にスタックが吹き飛ばされます。

さて、あなたのコードはそのような空の宣言を持っているようには見えませんinstance Showが、実際にはそうです: 間違ったインデントのために、showそこで定義したものは、たまたまと同名GHC.Show.show。追加できます

show :: PhisicalCell -> String

ファイルに追加して、今と同じ結果を取得します。

于 2013-09-19T12:07:43.723 に答える