Intermediate Variable Cache in Single Line

Is there any way to cache i.toString in this simple function definition?

 def palindrome(i: Int) = i.toString == i.toString.reverse 

I want this function to be simple, without the classic multi-line function enclosed in braces.

+4
source share
5 answers

You can do:

 def palindrome(i: Int) = ((s:String) => s == s.reverse)(i.toString) 
+6
source

Well, Scala does not have a let statement, like some traditional functional languages, but mainly because val + curly braces do the same. Do you mind the multi-line part or parentheses in general? Because it is quite difficult to defeat:

 def palindrome(i: Int) = { val s = i.toString; s == s.reverse } 

Attempts to remove curly braces are likely to lead only to an increase in the number of characters.

+6
source

Use the straight 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 resolves your problem decisively, I suggest changing the palindrome signature from palindrome(Int) to palindrome(String) and calling it with palindrome(i.toString) (and renaming it to isPalindrome ).

+5
source

This is a single line, but 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 can 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 } 
+3
source

It is required to refer to something exactly twice, often enough so that it is useful to enrich it in the 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 is a fairly common use case that you might want to create yourself.

(A diamond is here because it takes one value, breaks it into two parts, and combines it again again.)

0
source

All Articles