How to access the replaceAllIn() counter? - scala

I am using
val str2 = regex.replaceAllIn(str1, "other")
and need to count the number of replaces... There are a way retrieve the value of the internal replaceAllIn counter?
PS: this is usual in other languages (example), so I am supposing that Scala offer similar thing.

scala> val r = "x".r
r: scala.util.matching.Regex = x
scala> var i = 0
i: Int = 0
scala> r.replaceAllIn("xooxxox", m => { i += 1 ; "X" })
res0: String = XooXXoX
scala> i
res1: Int = 4
will do appendReplacement under the hood.

Takes another step but you could findAllIn and count the number found. Then do replaceAllIn.
scala> "foo".r.findAllIn("barbazfoobazfoo").size
res7: Int = 2

Related

Scala subString function

Hi I am looking for a solution it will return a substring from string for the given indexes.For avoiding index bound exception currently using if and else check.Is there a better approach(functional).
def subStringEn(input:String,start:Int,end:Int)={
// multiple if check for avoiding index out of bound exception
input.substring(start,end)
}
Not sure what you want the function to do in case of index out of bound, but slice might fit your needs:
input.slice(start, end)
Some examples:
scala> "hello".slice(1, 2)
res6: String = e
scala> "hello".slice(1, 30)
res7: String = ello
scala> "hello".slice(7, 8)
res8: String = ""
scala> "hello".slice(0, 5)
res9: String = hello
Try is one way of doing it. The other way is applying substring only if length is greater than end using Option[String].
invalid end index
scala> val start = 1
start: Int = 1
scala> val end = 1000
end: Int = 1000
scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res9: Option[String] = None
valid end index
scala> val end = 6
end: Int = 6
scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res10: Option[String] = Some(rayag)
Also, you can combine filter and map to .collect as below,
scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res14: Option[String] = Some(rayag)
scala> val end = 1000
end: Int = 1000
scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res15: Option[String] = None

How to use previous expression's result in Scala REPL?

// when in Scala REPL
scala> 1
res0: Int = 1
How can I reuse an expression's result in another expression?
For example:
scala> 1
res0: Int = 1
scala> the_previous_expression + 1
// = 2
You can reuse the previous expression's result by looking its REPL output on the next line, the word starting with res.
// when in Scala REPL
scala> 1
res0: Int = 1 // <-- res0 is the handle that you can use
For example:
scala> 1
res0: Int = 1
scala> res0 + 1
res1: Int = 2
scala> res1 + 1
res2: Int = 3
// and so on
You can also use it with others:
scala> () => "hey!" // anonymous function
res0: () => String = $$Lambda$1104/1658578510#6cff61fc
scala> res0()
res1: String = hey

One argument referencing another in the argument list

Occasionally, I encounter one argument wanting to reference another. For instance,
def monitor(time: Double, f: Double => Double, resolution: Double = time / 10) = {...}
Note that resolution refers to time. Are there languages where this is possible? Is it possible in Scala?
It is somewhat possible in Scala, but you have to curry the parameters:
def monitor(time: Double, f: Double => Double)(resolution: Double = time / 10)
You cannot do it in the way the question is posed.
I don't know any langage where this construction is possible, but a simple workaround is not difficult to find.
In scala, something like this is possible :
scala> def f(i : Int, j : Option[Int] = None) : Int = {
| val k = j.getOrElse(i * 2)
| i + k
| }
f: (i: Int, j: Option[Int])Int
scala> f(1)
res0: Int = 3
scala> f(1, Some(2))
res1: Int = 3
In scala, you can also make something like this :
scala> def g(i : Int)(j : Int = i * 2) = i + j
g: (i: Int)(j: Int)Int
scala> g(2)(5)
res6: Int = 7
scala> g(2)()
res7: Int = 6

Is there a way to initialize multiple variables from array or List in Scala?

What I want to do is basically the following in Java code:
String[] tempStrs = generateStrings();
final int hour = Integer.parseInt(tempStrs[0]);
final int minute = Integer.parseInt(tempStrs[1]);
final int second = Integer.parseInt(tempStrs[2]);
However, tempStrs is just a temporary variable, which is not used anymore. Then, this can be expressed in the following code in F#:
let [| hour; minute; second |] = Array.map (fun x -> Int32.Parse(x)) (generateStrings())
Is there a similar way to do this in Scala?
I know this can be done in Scala by
val tempInts = generateStrings().map(_.toInt)
val hour = tempInts(0)
val minute = tempInts(1)
val second = tempInts(2)
But is there a shorter way like F# (without temp variable)?
Edit:
I used
var Array(hour, minute, second) = generateStrings().map(_.toInt)
Of course, using val instead of var also worked.
How about this:
scala> val numbers = List(1, 2, 3)
numbers: List[Int] = List(1, 2, 3)
scala> val List(hours, minutes, seconds) = numbers
hours: Int = 1
minutes: Int = 2
seconds: Int = 3
To deal with three or more values, you could use:
scala> val numbers = List(1, 2, 3, 4)
numbers: List[Int] = List(1, 2, 3, 4)
scala> val num1 :: num2 :: num3 :: theRest = numbers
num1: Int = 1
num2: Int = 2
num3: Int = 3
theRest: List[Int] = List(4)
For a size-3 list theRest will simply be the empty list. Of course, it doesn't handle lists of two or fewer elements.

Int division in scala

I have two Int values in Scala.
scala> val a = 3
a: Int = 3
scala> val b = 5
b: Int = 5
Now, I want to divide them and get Float. With as little boilerplate as possible.
If I do a/b, I get
scala> a/b
res0: Int = 0
I cannot do simple Java (float).
scala> ((Float)a)/b
<console>:9: error: value a is not a member of object Float
((Float)a)/b
^
What should I do?
The following line followed by its result should solve your problem.
scala> a.toFloat/b
res3: Float = 0.6
Alternative answer that uses type ascription:
scala> (a:Float)/b
res0: Float = 0.6