各种编程语言验证“白马非马”的命题

时间:06/05/2022 19:19:44   作者:ChenReal    阅读:83

公孙龙系春秋战国时代诸子百家中“名家”的代表人物之一,他曾给出一个叫“白马非马”的命题。历经2000多年后仍被我们现代人所传诵,列诡辩的经典案例。 从逻辑学来看,该命题确实是诡辩。其实公孙龙做了一个概念的混淆,“白”是作为“马”这一概念的“颜色”内涵属性,“白马”是“马”的外延案例。 因此,“白马”和“马”两个抽象概念,是从属关系,可以用包含与被包含的关系来做逻辑描述,而不能用简单的“是”或“否”做比较。

逻辑学和哲学讨论就此打住。下面,我们看看一些编程语言是怎么对这个命题输出答案的,或许这更有意思。

Java代码

class Horse {
    public int Age;
    public int Height;
    public int Weight;
}
class WhiteHorse extends Horse {
    public String Color;
    public WhiteHorse(){
        this.Color = \"white\";
    }
}
public class Main {
    public static void main(String[] args) {
        WhiteHorse whiteHourse = new WhiteHorse();
            System.out.println(\"WhiteHorse is Horse?\");
            System.out.println(whiteHourse instanceof Horse);
    }
}

运行结果:

WhiteHorse is Horse?
true

C#代码

using System;
class Horse {
            public int Age {get;set;}
            public int Height {get;set;}
            public int Weight {get;set;}
    }

    class WhiteHorse : Horse{
            public string Color {get;set;}
            public WhiteHorse(){
                    Color = \"white\";
            }
    }
class Program
{
    public static void Main(string[] args)
    {
        var whiteHourse = new WhiteHorse();
        Console.WriteLine(\"WhiteHorse is Horse?\");
        Console.WriteLine(whiteHourse is Horse);
    }
}

运行结果:

WhiteHorse is Horse?
True

PHP代码

<?php
class Horse {
  var $age;
  var $height;
  var $weight;
}
class WhiteHorse extends Horse {
  var $color;
  function __construct() {
       $this->color = \"white\";
   }
}
$whiteHorse = new WhiteHorse;
print(\"WhiteHorse is Horse?\
\");
print($whiteHorse instanceof Horse);
?>

运行结果:

WhiteHorse is Horse?
1

TypeScript代码

class Horse {
    public Age:number;
    public Height:number;
    public Weight:number;
}
class WhiteHorse extends Horse {
    public Color:String;
    public WhiteHorse(){
        this.Color = \"white\";
    }
}
var whiteHourse:WhiteHorse = new WhiteHorse();
console.log(\"WhiteHorse is Horse?\");
console.log(whiteHourse instanceof Horse);

运行结果:

WhiteHorse is Horse?
true

golang代码

package main

import \"fmt\"
import \"reflect\"

type Horse struct{
    Age int32
    Height int32
    Weight int32
}

type WhiteHorse struct{
    Horse
    Color string
}

func main() {
    var whiteHorse WhiteHorse
    var horse Horse
    fmt.Println(\"WhiteHorse is Horse?\");
    fmt.Println(reflect.TypeOf(whiteHorse)==reflect.TypeOf(horse))
}

运行结果:

WhiteHorse is Horse?
false

结论

在OOP语言的世界中,“白马非马”是不成立的。而golang没有class的概念,用struct属于值类型,从而没有构成WhiteHorse继承Horse关系,因此结果输出是false。

 

评论
0/200