如何将Haskell对象作为有效Haskell代码的字符串输出到输出中,省略现有的show
声明?
例如,我有以下类型声明和相应的show
声明(check the code out in an online IDE):
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
import Data.Maybe
type VersionCompound = Maybe Int
data VersionNumber = VersionNumber [VersionCompound] deriving (Show)
data MaturityLevel = Dev
| Test
| User
| ReleaseCandidate
| Prod
deriving (Show)
data Version = MaturityVersion MaturityLevel VersionNumber
| Version VersionNumber
class ToString a where
toString :: a -> String
instance ToString VersionCompound where
toString (Just n) = (show n)
toString Nothing = "x"
instance ToString [VersionCompound] where
toString [] = ""
toString (x:[]) = (toString x)
toString (x:xs) = (toString x) ++ "." ++ (toString xs)
instance ToString VersionNumber where
toString (VersionNumber []) = ""
toString (VersionNumber (x:[])) = (toString x)
toString (VersionNumber (x:xs)) = (toString x) ++ "." ++ (toString xs)
instance ToString Version where
toString (MaturityVersion maturityLevel versionNumber) = (show maturityLevel) ++ "/" ++ (toString versionNumber)
toString (Version versionNumber) = (toString versionNumber)
instance Show Version where
show version = toString version
main = putStrLn $ show (Version $ VersionNumber [ Just 1, Just 2, Nothing])
该计划的输出是:
1.2.x
但是有没有办法以有效的Haskell代码形式输出对象?例如,对于上面的代码,showIntact $ Version $ VersionNumber [ Just 1, Just 2, Nothing]
会输出如下内容:
Version ( VersionNumber [ Just 1, Just 2, Nothing] )
答案 0 :(得分:4)
您可以定义自己的功能:
showIntact :: Version -> String
showIntact (Version v) = "Version " ++ show v
showIntact (MaturityVersion ml vn) = "MaturityVersion " ++ show ml ++ " " ++ show vn
然后,您可以使用putStrLn $ showIntact $ ....
。