自然数如何表现为提供恒定的时间添加? [英] How can natural numbers be represented to offer constant time addition?

查看:139
本文介绍了自然数如何表现为提供恒定的时间添加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Cirdec的答案与一个很无关系的问题让我想知道如何最好地用常量加法来表示自然数,减法为什么Peano算术不够好:

假设我们使用

  data Nat = Z | S $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ p p p p p p p p p p p p p p p p p $ p>  Z + n = n 
S m + n = S(m + n)

我们可以通过将 mr 借方计算在O(1)时间内计算 m + n (对于一些常量 r ),每个 S 构造函数中的一个添加到 n 。要获得O(1) isZero ,我们需要确保最多只有 p 每个 S 构造函数,对于一些常量 p 。如果我们计算 a +(b +(c + ...)),这可能很好,但如果我们计算((...) + b)+ c)+ d 。麻烦的是,这个借记在前端堆叠。



一个选项



简单的出路是直接使用Okasaki描述的连接列表。有两个问题:


  1. O(n)空间不是很理想。


  2. 我们不太在乎(至少对我来说)当我们不关心订单时,引导队列的复杂性是必要的。



解决方案

据我所知,Idris(一个非常接近Haskell的依赖类型的纯功能语言)以一种相当简单的方式来处理这个问题。编译器知道 Nat s和 Fin s(upper-bounded Nat s),并尽可能用机器整数类型和操作替换它们,因此生成的代码是非常有效的。然而,对于自定义类型(甚至是同构的)以及编译阶段(有些代码示例使用 Nat 来进行类型检查,这导致了指数增长,这并不正确编译时,如果需要,我可以提供它们)。



在Haskell的情况下,我认为可以实现类似的编译器扩展。另一种可能性是使TH宏变换代码。当然,这两个选项都不容易。


Cirdec's answer to a largely unrelated question made me wonder how best to represent natural numbers with constant-time addition, subtraction by one, and testing for zero.

Why Peano arithmetic isn't good enough:

Suppose we use

data Nat = Z | S Nat

Then we can write

Z + n = n
S m + n = S(m+n)

We can calculate m+n in O(1) time by placing m-r debits (for some constant r), one on each S constructor added onto n. To get O(1) isZero, we need to be sure to have at most p debits per S constructor, for some constant p. This works great if we calculate a + (b + (c+...)), but it falls apart if we calculate ((...+b)+c)+d. The trouble is that the debits stack up on the front end.

One option

The easy way out is to just use catenable lists, such as the ones Okasaki describes, directly. There are two problems:

  1. O(n) space is not really ideal.

  2. It's not entirely clear (at least to me) that the complexity of bootstrapped queues is necessary when we don't care about order the way we would for lists.

解决方案

As far as I know, Idris (a dependently-typed purely functional language which is very close to Haskell) deals with this in a quite straightforward way. Compiler is aware of Nats and Fins (upper-bounded Nats) and replaces them with machine integer types and operations whenever possible, so the resulting code is pretty effective. However, that's not true for custom types (even isomorphic ones) as well as for compilation stage (there were some code samples using Nats for type checking which resulted in exponential growth in compile-time, I can provide them if needed).

In case of Haskell, I think a similar compiler extension may be implemented. Another possibility is to make TH macros which would transform the code. Of course, both of options aren't easy.

这篇关于自然数如何表现为提供恒定的时间添加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆