2014-02-21 22 views
2

我要實現一個顯示實例與類型哈斯克爾:顯示與類型,如:: *數據 - > *

這裏一個數據類型的問題是代碼:

data RMcom = LOAD Int | STORE Int | CLOAD Integer | CADD Integer | 
      CSUB Integer | CMULT Integer | CDIV Integer | ADD Int | 
      SUB Int | MULT Int | DIV Int | GOTO Integer | JZERO Integer | 
      END deriving (Eq, Show, Read) 

type RMprog = Integer -> RMcom 

type Register = Int -> Integer 

data RMstate = State {progr :: RMprog, pc :: Integer, reg :: Register, maxReg :: Int} 

其仿真對於Registermachine

所以現在我想爲我自己製作一個Show RMstate實例。

Normaly我會做這樣的

instance Show RMstate where 
    show(State progr pc reg maxReg) = show(progr)++show(pc)++show(reg)++show(maxReg) 

但是編譯器要對顯示RMprog和註冊一個實例,但我怎麼 可以爲一個類型的實例?

預先感謝

回答

10

RMProgRegister類型的功能。一般來說,函數不能以任何有趣的方式顯示。你可以通過導入Text.Show.Functions得到一些東西,但它可能不是你想要的。

我建議你使用newtype這兩種類型,並編寫你自己的Show實例來做更好的事情。

E.g.

newtype Register = Register (Int -> Integer) 
instance Show Register where 
    show (Register f) = "Registers:" ++ show [(i, f i) | i <- [0..15] ] 
+0

任何可能得到它的工作,無需額外進口,只是在節目的功能? –

+1

是的,您可以爲'Show(a - > b)'編寫自己的實例。 – augustss

1

可以這樣做

instance Show (x -> y) where 
    show _ = "<function>" 

然後代碼將工作 ...它不會告訴你多少的利息,但它會工作

(這基本上就是進口Text.Show.Functions沒有。)

個人而言,我會去從augustss的建議,但它是由您決定。

0

明白了:

instance Show RMstate where 
show (State prog i reg k) = 
    "\n"++"naechster Befehl: "++(show $ prog i)++"\n"++"Registerbelegungen: \n"++ 
    (concat [ (show i)++": "++(show $ reg i)++"\n" | i <- [0..k]]) 
1
import Data.Maybe (fromJust) 

我已經採取了增加maxProg :: Integer的自由,所以我們知道在哪裏停止RMprog

data RMstate = State {progr :: RMprog, pc :: Integer, reg :: Register, 
         maxReg :: Int, maxProg::Integer} 

首先,讓我們做一個功能,顯示像RMprogRegister線功能的時間,因此例如,

ghci> putStrLn $ showIndexed (+100) 1 
1  101 

這樣的:

showIndexed :: (Show i, Show v) => (i -> v) -> i -> String 
showIndexed f i = show i ++ '\t':show (f i) 

現在我們可以顯示RMstate,通過輸出的線粘合在一起:

instance Show RMstate where 
    show s = unlines $ 
       ["","Program:"] 
       ++ [showIndexed (progr s) i | i <- [0..maxProg s]] 
       ++ ["","PC:\t"++show (pc s),"","Registers:"] 
       ++ [showIndexed (reg s) i | i <- [0..maxReg s]] 


example = State {progr=p, pc=3, reg=r, maxReg=15, maxProg=10} where   
    p = fromJust.flip lookup (zip [0..] [LOAD 3, STORE 2, CLOAD 1, 
              CADD 12, CSUB 4, CMULT 5, 
              CDIV 2, ADD 123, SUB 10, 
              MULT 5, DIV 2, GOTO 6, 
              JZERO 4, END]) 

    r = fromJust . flip lookup (zip [0..] [3,4,3,5,6,5,2,5,7,2,4,5,672,5,56,3]) 

它看起來像:

ghci> print example 

Program: 
0  LOAD 3 
1  STORE 2 
2  CLOAD 1 
3  CADD 12 
4  CSUB 4 
5  CMULT 5 
6  CDIV 2 
7  ADD 123 
8  SUB 10 
9  MULT 5 
10  DIV 2 

PC:  3 

Registers: 
0  3 
1  4 
2  3 
3  5 
4  6 
5  5 
6  2 
7  5 
8  7 
9  2 
10  4 
11  5 
12  672 
13  5 
14  56 
15  3