你的问题不清楚,那我就从转换开始吧:
toPeano 0 = Zero
toPeano 1 = Succ Zero
toPeano 2 = Succ (Succ Zero)
这是相当明确的。您可以使用简单的递归来定义 Peano 数,并使其适用于所有自然数:
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)) - 这只是从整数中减一,然后在 Peano 结构中加一。
现在另一个方向呢?好吧,每次看到“成功”时,您都可以添加一个:
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 (...