For a homework assignment, I am being asked to merge two lists of integers in non-decreasing order. We are told not to "not use the if operator."
I can merge the two lists through recursion without any difficulty (if I ignore the non-decreasing part), but how I do I compare one integer from each list without using an if statement? From what I've seen, the Scala match feature does not allow开发者_如何学Go expressions, but I'm unsure how to utilize that in this case.
Not necessarily looking for explicit answers / code samples, just looking for hints towards the right direction.
Thanks.
You can use the max
and min
methods to allow you to cons both numbers on to the result in the proper non-decreasing order. Be sure to prove (at least to yourself) that this works in all cases.
There's lots of way of doing this without using the if
statement, but still resorting to comparing the numbers. That would be simply hiding an implicit if
statement behind something else.
One alternative to if
statements in object-oriented languages is polymorphism. Consider this:
sealed trait Bool
object Bool {
def apply(b: Boolean): Bool = b match {
case true /* Implicit if! */ => True
case false => False
object True extends Bool
object False extends Bool
From a Boolean
you can construct a Bool
(using an implicit if
, granted). You can then add a method to Bool
, implementing it differently for each object
. This is how Option
works, by the way. None
has one implementation, and Some
has another.
There's one way to avoid comparing the numbers, however. If you don't compare, you don't use if
either -- not even implicitly. Fun fact: a computer magazine back in the 80s had a contest for sorting algorithms, the winner of which would be the one comparing the fewest time. The winning algorithm sorted entirely without comparing, and then did a dummy compare just to stay within the rules of the contest.
The tip here is that you have to know what the range of the numbers is, and that range cannot be too big, or, otherwise, you'll have to do multiple passes to finish the ordering. Also, lists are inefficient to perform the operations.
I hope this helps.
Don't do this. But, hilariously, it works. Let's assume you're comparing x and y.
val okay = Array(0,1)
try {
b(math.signum(x.toLong - y.toLong).toInt)
// Handle x >= y case here
}
catch { case _ =>
// Handle x < y case here
}
You could also
val handler = Array(
() => {
// Handle x < y
},
() => {
// Handle x == y
},
() => {
// Handle x > y
}
)
handler(math.signum(x.toLong-y.toLong).toInt+1)()
which is slightly less silly (but still rather silly).
精彩评论