how to implement variable length argument function in scala - scala

I have to concatenate k different lengths of strings into one string res and save res string into ArrayBuffer[String]().
But the k is variable.
For example,
val result = new ArrayBuffer[String]()
result.+=("1\t" + A.toString() + "\t" + ls.pid + "\t" + ls.did + "\t" + ls.sid + "\t" + ls.request_time.substring(0,10))
result.+=("2\t" + B.toString() + "\t" + ls.pid + "\t" + ls.did + "\t" + ls.sid + "\t")
result.+=("2\t" + B.toString() + "\t" + ls.pid + "\t" + ls.did + "\t")
result.+=("2\t" + B.toString() + "\t")
How to use a function with a variable-length argument to implement it?
Thanks in advance.

You can use the following syntax:
def f(args: String*) = {
args.map{s =>
//todo: process single item
s
}
}

Related

How to get RDD[List[String]] to String and split it

I have below scenario , when I need to get the lines from list and split it.
scala> var nonErroniousBidsMap = rawBids.filter(line => !(line(2).contains("ERROR_") || line(5) == null || line(5) == ""))
nonErroniousBidsMap: org.apache.spark.rdd.RDD[List[String]] = MapPartitionsRDD[108] at filter at <console>:33
scala> nonErroniousBidsMap.take(2).foreach(println)
List(0000002, 15-04-08-2016, 0.89, 0.92, 1.32, 2.07, , 1.35)
List(0000002, 11-05-08-2016, 0.92, 1.68, 0.81, 0.68, 1.59, , 1.63, 1.77, 2.06, 0.66, 1.53, , 0.32, 0.88, 0.83, 1.01)
scala> val transposeMap = nonErroniousBidsMap.map( rec => ( rec.split(",")(0) + "," + rec.split(",")(1) + ",US" + "," + rec.split(",")(5) ) )
<console>:35: error: value split is not a member of List[String]
val transposeMap = nonErroniousBidsMap.map( rec => ( rec.split(",")(0) + "," + rec.split(",")(1) + ",US" + "," + rec.split(",")(5) ) )
^
I am getting an error as showed above.
Can you please help me how to solve this ?
Thank you.
The type of rec is List[String] - which does not have a split(String) method (as the compiler correctly warns). It looks like you're assuming your records are comma-separated Strings, but in fact they're not (when you call println on each one of them, they are printed with comma separators simply because that's how List.toString behaves).
You can simply remove all the calls to split(",") and get what you want:
nonErroniousBidsMap.map(rec => rec.head + "," + rec(1) + ",US" + "," + rec(5))
Or even more elegantly, using Scala's String Interpolation:
nonErroniousBidsMap.map(rec => s"${rec.head},${rec(1)},US,${rec(5)}")

Anyone knows Reduce Boolean Expression

Anyone can help me reduce this to 4 literals?
F = ( A + C + D) ( A + C + D') (A + C' + D) ( A + B')
i tested in logic friday the answer was F = C D B' + A.
Assuming the ⋅ operator represents binary conjunction, the + binary disjunction and the ' or the ¬ unary negation, I would apply the laws of Boolean algebra this way:
(a + c + d)⋅(a + c + ¬d)⋅(a + ¬c + d)⋅(a + ¬b)
((a + d) + (c⋅¬c))⋅(a + c + ¬d)⋅(a + ¬b) //distributivity
((a + d) + (0))⋅(a + c + ¬d)⋅(a + ¬b) //complementation: c⋅¬c = 0
(a + d)⋅(a + c + ¬d)⋅(a + ¬b) //identity for +: (a + d) + (0) = (a + d)
(a) + (d⋅(c + ¬d)⋅¬b) //distributivity
(a) + ((d⋅c + d⋅¬d))⋅¬b) //distributivity: d⋅(c + ¬d) = (d⋅c + d⋅¬d)
(a) + ((d⋅c + 0))⋅¬b) //complementation: d⋅¬d = 0
(a) + (d⋅c⋅¬b) //identity for +: (d⋅c + 0) = d⋅c
a + ¬b⋅c⋅d
The final line is the minimal DNF. You can also transform it to it's minimal CNF this way:
(a) + (¬b⋅c⋅d)
(a + ¬b)⋅(a + c)⋅(a + d) //distributivity
For this small number of variables, you could have used Karnaugh maps to quickly find the minimal forms or to control your result. In the following picture (generated using latex) is the original expression next to it's minimal DNF and minimal CNF.
After finding the mean term you can use
Quine McCluskey Technique to solve the experssion. The result will same as K-Map. But it is fast technique for many veriable boolean expression.
Quine McCluskey online solver

The product of sums in boolean function

I have a function
A'B'C + AC'D + ABC + BC'D'
I have simplified to
C(A'B' + AB) + C'(AD + BD')
(C + AD + BD')(C' A'B' + AB)
Is this the right course? The last step is where I am getting stuck.

Scala closures and underscore (_) symbol

Why I can write something like this without compilation errors:
wordCount foreach(x => println("Word: " + x._1 + ", count: " + x._2)) // wordCount - is Map
i.e. I declared the x variable.
But I can't use magic _ symbol in this case:
wordCount foreach(println("Word: " + _._1 + ", count: " + _._2)) // wordCount - is
You should check this answer about placeholder syntax.
Two underscores mean two consecutive variables, so using println(_ + _) is a placeholder equivalent of (x, y) => println(x + y)
In first example, you just have a regular Tuple, which has accessors for first (._1) and second (._2) element.
it means that you can't use placeholder syntax when you want to reference only one variable multiple times.
Every underscore is positional. So your code is desugared to
wordCount foreach((x, y) => println("Word: " + x._1 + ", count: " + y._2))
Thanks to this, List(...).reduce(_ + _) is possible.
Moreover, since expansion is made relative to the closest paren it actually will look like:
wordCount foreach(println((x, y) => "Word: " + x._1 + ", count: " + y._2))

How do I invoke the '!=' method on an object?

I just started playing with scala and have been using the "Scala By Example" by Michel Schinz ( http://www.scala-lang.org/node/198 ) as a starting point. In the segment on traits, I've attempted to use reflection/method invocation to test traits and wanted to test all the comparison operator. I hit the issue with name mangling and found the solution in NameTransformer for the operators. However, the != operator, appears to me that it does not translate into an equivalent function like <, <=, >, >=, equals. I wonder if there is a way to invoke != much like the other operators that I have not found out?
From the pdf:
trait ord {
def < (that:Any):Boolean
def <= (that:Any):Boolean = (this < that) || (this == that)
def > (that:Any):Boolean = !(this <= that)
def >= (that:Any):Boolean = !(this < that)
}
class Date(y:Int, m:Int, d:Int) extends ord{
def year = y
def month = m
def day = d
override def toString():String = year + "-" + month + "-" + day
override def equals(that:Any): Boolean =
that.isInstanceOf[Date] && {
val o = that.asInstanceOf[Date]
o.day == this.day && o.month == this.month && o.year == this.year
}
override def <(that:Any):Boolean = {
if (!that.isInstanceOf[Date])
error("Cannot compare " + that + " and date")
val o = that.asInstanceOf[Date]
(year < o.year) ||
(year == o.year && (month < o.month ||
(month == o.month && day < o.day )))
}
}
My code:
def Classes_Traits(){
val (d1, d2, d3) = (new Date(2001, 10, 1), new Date(2001, 10, 1), new Date(2000, 1, 10))
println("d1 : " + d1)
println("d2 : " + d2)
println("d3 : " + d3)
Array((d1,d2), (d2,d3), (d3,d1)).foreach {
(comp:(Date, Date)) =>
println("comparing " + comp._1 + " and " + comp._2)
val d = comp._1.getClass()
Map(
"equals " -> "equals",
"not equals " -> "!=",
"less than " -> "<",
"less than or equal" -> "<=",
"more than " -> ">",
"more than or equal" -> ">=").foreach {
(a) =>
println(a._1 + " : " +
d.getMethod(scala.reflect.NameTransformer.encode(a._2),
classOf[Object]).invoke(comp._1, comp._2))
}
/*println("equals : " + m.invoke(comp._1, comp._2) )
// Same as above
println(comp._1 + " == " + comp._2 + " is " + (comp._1 == comp._2))
println(comp._1 + " != " + comp._2 + " is " + (comp._1 != comp._2))
println(comp._1 + " > " + comp._2 + " is " + (comp._1 > comp._2))
println(comp._1 + " >= " + comp._2 + " is " + (comp._1 >= comp._2))
println(comp._1 + " < " + comp._2 + " is " + (comp._1 < comp._2))
println(comp._1 + " <= " + comp._2 + " is " + (comp._1 <= comp._2))
*/
}
}
exception:
comparing 2001-10-1 and 2001-10-1
more than or equal : true
more than : false
Exception in thread "main" java.lang.NoSuchMethodException: proj2.Main$Date.$bang$eq(java.lang.Object)
at java.lang.Class.getMethod(Class.java:1605)
at proj2.Main$$anonfun$Classes_Traits$1$$anonfun$apply$1.apply(Main.scala:180)
at proj2.Main$$anonfun$Classes_Traits$1$$anonfun$apply$1.apply(Main.scala:178)
at scala.collection.immutable.HashMap$HashMap1.foreach(HashMap.scala:125)
at scala.collection.immutable.HashMap$HashTrieMap.foreach(HashMap.scala:344)
at proj2.Main$$anonfun$Classes_Traits$1.apply(Main.scala:177)
at proj2.Main$$anonfun$Classes_Traits$1.apply(Main.scala:168)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:34)
at scala.collection.mutable.ArrayOps.foreach(ArrayOps.scala:35)
at proj2.Main$.Classes_Traits(Main.scala:167)
at proj2.Main$.main(Main.scala:26)
at proj2.Main.main(Main.scala)
Try calling equals and negating the result. == and != benefit from a little compiler magic in Scala (e.g., you can call null.==(4) without getting a NullPointerException).