Reputation: 557
Just wondering if anyone would know how to make the following if statement more functional:
val value1 = 8
val value2 = 10
if(val1 > val2){
println("\n" + stock1 + " has the highest current value")
}else if(val1 < val2){
println("\n" + stock2 + " has the highest current value")
}else if(val1 == val2)){
println("\nThe current value for " + stock1 + " is equal the current value for " + stock2)
}
I would be very grateful if someone could make a suggestion.
Thanks
Upvotes: 2
Views: 957
Reputation: 381
I think the key thing about being functional here is to separate calculation from effects.
Your snippet is both calculating the message to print and doing IO. There's nothing wrong with using if statements -- in this case I'd say it's the clearest way to write it.
val value1 = 8
val value2 = 10
def valueMessage =
if (val1 > val2) stock1 + " has the highest current value"
else if (val1 < val2) stock2 + " has the highest current value"
else "The current value for " + stock1 + " is equal the current value for " + stock2
def printValueMessage() = println("\n" + valueMessage)
printValueMessage() // unsafe
Upvotes: 4
Reputation: 15086
Like this? What do you think is not functional enough about your solution?
println(
if (val1 > val2)
s"\n$stock1 has the highest current value"
else if (val1 < val2)
s"\n$stock2 has the highest current value"
else
s"\nThe current value for $stock1 is equal the current value for $stock2"
)
Upvotes: 1
Reputation: 9820
Using cats-kernel you could use Order[Int].comparison
:
import cats.kernel.Order
import cats.kernel.instances.int._
import cats.kernel.Comparison._
val message =
Order[Int].comparison(val1, val2) match {
case GreaterThan => s"$stock1 has the highest current value"
case LessThan => s"$stock2 has the highest current value"
case EqualTo =>
s"The current value for $stock1 is equal the current value for $stock2"
}
println(s"\n$message")
Upvotes: 6
Reputation: 4161
Or this:
math.signum(value1 - value2) match {
case -1 => println("v1 <= v2")
case 1 => println("v1 >= v2")
case _ => println("v1 == v2")
}
Upvotes: 1
Reputation: 8263
match
, if you like it
val1 match{
case v if v > val2 => println("\n" + stock1 + " has the highest current value")
case v if v < val2 => println("\n" + stock2 + " has the highest current value")
case _ => println("\nThe current value for " + stock1 + " is equal the current value for " + stock2)
}
Upvotes: 4