Why do most programming languages only have binary equality comparison operators?

前端 未结 24 1010
一个人的身影
一个人的身影 2020-12-08 14:20

In natural languages, we would say \"some color is a primary color if the color is red, blue, or yellow.\"

In every programming language I\'ve seen, that translates

24条回答
  •  生来不讨喜
    2020-12-08 14:47

    It's because programming languages are influenced by mathematics, logic and set theory in particular. Boolean algebra defines ∧, ∨ operators in a way that they do not work like spoken natural language. Your example would be written as:

    Let p(x) be unary relation which holds if and only if x is a primary color
    p(x) ⇔ r(x) ∨ g(x) ∨ b(x)
    or
    p(x) ⇔ (x=red) ∨ (x=green) ∨ (x=blue)
    

    As you see, it's pretty similar to notation that would be used in programming language. As mathematics provide strong theoretic foundations, programming languages are based on mathematics rather than natural language which always leaves a lot of space for interpretation.

    EDIT: Above statement could be simplified by using set notation:

    p(x) ⇔ x ∈ {red, green, blue}
    

    and indeed, some programming languages, most notably Pascal, included set, so you could type:

    type
        color = (red, green, blue, yellow, cyan, magenta, black, white);
    
    function is_primary (x : color) : boolean;
    begin
        is_primary := x in [red, green, blue]
    end
    

    But sets as a language feature didn't catch on.

    PS. Sorry for my imperfect English.

提交回复
热议问题