的情況下我有一個用戶定義的數據結構中的問題和Read
匹配[字符]來讀取
首先這裏的情況是我的數據結構
data Nat = Null | Succ Nat
我讀函數定義這樣
readNatNat :: String -> Nat
readNatNat xs |first == '(' = readNatNat (tail xs)
|first == ' ' = readNatNat (tail xs)
|firstFour == "Succ" = (Succ (readNatNat(drop 4 xs)))
|firstFour == "Null" = Null
|b `elem` [0..] = toNatInt(b)
where b = (read(xs)::Int)
first = head xs
firstFour = take 4 xs
toNatInt :: Int -> Nat
toNatInt x | x==0 = Null
| x<0 = error "Unter Null gibts kein Int 2 Nat"
| otherwise = Succ(toNatInt(x-1))
readNatNat
作爲獨立功能的正常工作,但是當我想用Read
情況下使用它,並嘗試加載它我得到下面的異常
Couldn't match type `[Char]' with `Int'
Expected type: Int -> ReadS Nat
Actual type: String -> Nat
In the expression: readNatNat
In an equation for `readsPrec': readsPrec = readNatNat
In the instance declaration for `Read Nat'
Failed, modules loaded: none.
編程其他實例一樣Enum
,Eq
,Show
等是非常簡單的。 據我所知,Read
預計的詮釋,但我不知道爲什麼;)
我想Read
是show
相反的,並採取了String
並將其解析爲我的數據結構。
我定義Show
這樣
instance Show Nat where
show (Succ a) = showsRealSucc(Succ a)
show Null = show "Null"
showsRealSucc :: Nat -> String
showsRealSucc Null = "Null"
showsRealSucc (Succ a) = (if a/= Null then ("Succ ("++showsRealSucc(a)++")")
else "Succ Null")
爲了您的Nat
理解:
及其對自然數的表示,所以當我鍵入readNatNat "3"
輸出爲預先 "(Succ(Succ(Succ Null)))"
謝謝!
請爲您提供'Read'實例。 – crockeea
如果你看看'Read'類,你會看到它定義了函數'readsPrec :: Int - > String - > [(a,String)]''。你的功能顯然沒有這種類型。第一個參數是一個優先級上下文,用於更開明的解析。返回類型必須是解析列表和其餘字符串。要將你的函數轉換成有效格式,你可以寫'readsPrec _ x = [(readNatNat x,「」)]' – user2407038
@ user2407038的確。信不信由你,我只是在我的回答中這麼說,但我想我有點被帶走了! – AndrewC