【问题标题】:Haskell Peano NumbersHaskell Peano 数字
【发布时间】:2011-10-06 02:02:53
【问题描述】:

我正在尝试写一个函数

toPeano :: Int -> Nat
toPeano n =

将整数转换为其皮亚诺数。

我有数据:

data Nat =
   Zero |
   Succ Nat
   deriving Show

例如,

toPeano 0 = Zero
toPeano 1 = Succ Zero
toPeano 2 = Succ (Succ Zero)

等等。

我不知道如何让它打印出给定整数的皮亚诺数。我从未使用过 Peano 号码,因此我们将不胜感激!

谢谢!

【问题讨论】:

    标签: haskell integer peano-numbers


    【解决方案1】:

    你的问题不清楚,那我就从转换开始吧:

    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 (...
    

    【讨论】:

    【解决方案2】:

    您会寻找这样的东西吗?

    toPeano 0 = Zero
    toPeano n = Succ $ toPeano (n-1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多