你的問題是不明確的,所以我會從轉換開始:
toPeano 0 = Zero
toPeano 1 = Succ Zero
toPeano 2 = Succ (Succ Zero)
這是相當明確的。你可以用一個簡單的遞歸定義皮亞諾號和有工作的所有土黃:
toPeano 0 = Zero
toPeano x
| x < 0 = error "Can not convert a negative number to Peano"
| otherwise = Succ (toPeano (x-1))
這裏的核心是Succ (toPeano (x-1))
- 這只是一個減去從整並加1皮亞諾建築。
現在怎麼樣的另一個方向呢?好了,每次你看到一次「SUCC」你可以再補充一個:
fromPeano Zero = 0
fromPeano (Succ x) = 1 + fromPeano x -- note this is inefficent but right now we don't care
打印結果
現在你說的話,看上去像一個問題是隻有部分:
我不知道如何讓它打印出一個整數的Peano數字。
這有什麼好做皮亞諾的數字,但在GHCI你可以運行這些功能:
> fromPeano (toPeano 5)
5
或者你可以做一個程序,並使用print
打印出結果:
main = print (toPeano 5829)
,並使用GHC編譯程序
$ ghc --make myProg.hs
$ ./myProg
Succ (Succ (Succ (...
是,能夠避免通過使用某種類型的'Natural'號碼類型的此'檢查<0'? –
當然,我使用GADT在一個問題中編碼二進制([http://stackoverflow.com/questions/11910143/positive-integer-type/11912348#11912348]),並確定有其他方法可以做到這一點。 –