【问题标题】:Is there a programming language which allows the redefinition of numbers?是否有允许重新定义数字的编程语言?
【发布时间】:2016-10-16 18:34:29
【问题描述】:

我第一次解决这个问题是在 C 语言中

#define 2 5
assert(2+2 == 10);

很遗憾

error: macro name must be an identifier

我也试过Scheme

(define 2 5)

但是

can't define a non-symbol: (define 2 5)

我想知道是否有任何编程语言可以做到这一点。

【问题讨论】:

  • 只是一个想法,但在 C++ 中可能会重载 + 运算符,然后重新定义每个操作数在加法过程中的行为方式。
  • @TimBiegeleisen:这很困难,例如,2 + 2 是一个编译时可评估的常量表达式。我在标准 C++ 中看不到这样做的方法。
  • 你为什么要问?想知道要避免哪些语言?
  • @TimBiegeleisen 这是个好主意。不幸的是,我认为您不能为 int 等内置类型重载运算符。我试图定义一个类,在其上重载+int 运算符,然后将数字文字转换为该新类。这给出了看起来像 (T)2 + (T)2 == 5 的代码。这看起来很奇怪和可疑,但很酷,谢谢。 :)

标签: programming-languages flexibility


【解决方案1】:

我真心希望不要。

但话虽如此,我确实知道 Java 中的一种方法:您可以使用 reflection 来调整缓存的装箱 Integers 的值:JVM 必须缓存该范围内的所有值 - 128 到 +127,并且确实存在一种机制来调整该缓存中的数值!

请参阅https://codegolf.stackexchange.com/questions/28786/write-a-program-that-makes-2-2-5/28818#28818 了解更多详情。这是完整的代码:

import java.lang.reflect.Field;
public class Main {
    public static void main(String[] args) throws Exception {
        Class cache = Integer.class.getDeclaredClasses()[0];
        Field c = cache.getDeclaredField("cache");
        c.setAccessible(true);
        Integer[] array = (Integer[]) c.get(cache);
        array[132] = array[133];

        System.out.printf("%d", 2 + 2);
    }
}

输出为5,本质上是通过重新定义数字4来实现的。

【讨论】:

  • 我对安装 Java 有点不满,但它确实有效。这很酷,谢谢你的回答。抱歉,我没有足够的虚拟 stackoverflow 积分来投票。
猜你喜欢
  • 2013-09-06
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多