Domanda

There's a certain over-verbosity that I have to engage in when writing certain Boolean expressions, at least with all the languages I've used, and I was wondering if there were any languages that let you write more concisely?

The way it goes is like this:

I want to find out if I have a Thing that can be either A, B, C, or D.

And I'd like to see if Thing is an A or a B.

The logical way for me to express this is

//1:  true if Thing is an A or a B
Thing == (A || B)

Yet all the languages I know expect it to be written as

//2:  true if Thing is an A or a B
Thing == A || Thing == B

Are there any languages that support 1? It doesn't seem problematic to me, unless Thing is a Boolean.

È stato utile?

Soluzione

Yes. Icon does.

As a simple example, here is how to get the sum of all numbers less than 1000 that are divisble by three or five (the first problem of Project Euler).

procedure main ()
    local result
    local n
    result := 0
    every n := 1 to 999 do
        if n % (3 | 5) == 0 then
            result +:= n
    write (result)
end

Note the n % (3 | 5) == 0 expression. I'm a bit fuzzy on the precise semantics, but in Icon, the concept of booleans is not like other languages. Every expression is a generator and it may pass (generating a value) or fail. When used in an if expression, a generator will continue to iterate until it passes or exhausts itself. In this case, n % (3 | 5) == 0 is a generator which uses another generator (3 | 5) to test if n is divisible by 3 or 5. (To be entirely technical, this isn't even syntactic sugar.)

Likewise, in Python (which was influenced by Icon) you can use the in statement to test for equality on multiple elements. It's a little weaker than Icon though (as in, you could not translate the modulo comparison above directly). In your case, you would write Thing in (A, B), which translates exactly to what you want.

Altri suggerimenti

There are other ways to express that condition without trying to add any magic to the conditional operators.

In Ruby, for example:

$> thing = "A"
 => "A"
$> ["A","B"].include? thing
 => true 

I know you are looking for answers that have the functionality built into the language, but here are two other means that I find work better as they solve more problems and have been in use for many decades.

Have you considered using a preprocessor?

Also languages like Lisp have macros which is part of the language.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top