Can I somehow cache the i.toString
in this simple definition of function?
def palindrome(i: Int) = i.toString == i.toString.reverse
I want to keep this function simple, w/o a classic multi-line, brace-enclosed function..
You could do:
def palindrome(i: Int) = ((s:String) => s == s.reverse)(i.toString)
Well, Scala doesn't have a let statement like some traditional functional languages, but that's largely because val + braces fulfill the same purpose. Are you objecting to the multi-line part or to braces in general? Because it's pretty hard to beat:
def palindrome(i: Int) = { val s = i.toString; s == s.reverse }
Attempts to elide the braces will likely only drive the character count up.
Use the forward pipe operator:
scala> implicit class PipedObject[A](value: A) {
| def |>[B](f: A => B): B = f(value)
| }
defined class PipedObject
scala> def palindrome(i: Int) = i.toString |> (s => s == s.reverse)
palindrome: (i: Int)Boolean
While this solves your problem elegantly I advise to change the signature of palindrome
from palindrome(Int)
to palindrome(String)
and call it with palindrome(i.toString)
(and rename it to isPalindrome
).
It is a one-liner, but the braces are still here. It seems shorter to me, though:
def palindrome(i: Int) = { val s = i.toString; s == s.reverse }
If you have many such functions, you could also do something like this:
@inline def let[T, R](expr: =>T)(body: T => R): R = body(expr)
def palindrome(i: Int) = let(i.toString) { s => s == s.reverse }
Starting Scala 2.13
, the standard library provides the chaining operation pipe
which can be used to convert/pipe i.toString
with the function checking if a string is a palindrome:
import scala.util.chaining._
def palindrome(i: Int) = i.toString.pipe(s => s == s.reverse)
Needing to refer to something exactly twice comes up often enough that it's useful to have enrich it into a method:
implicit class DiamondMapper[A](val a: A) extends AnyVal {
def diamond[B](f: (A,A) => B) = f(a,a)
}
Then:
scala> 575.toString.diamond(_ == _.reverse)
res1: Boolean = true
This is a special case of the pipe operator (|>
if you like symbolic notation), but it's a common enough use case that you might want to create your own.
(Diamond here because it takes one value, splits it in two, and merges it back together again.)