Can I create empty Tuple or String in Scala? - scala

I need return tuple , but if something goes wrong I want return empty tuple, like Seq.empty[Type] or Nil in Lists. Is it possible?
Also I am curious about is it possible with String type.

I want return empty tuple
That doesn't make sense. A tuple is not a collection. The idea of "emptiness" is simply non-sensical. The length of a tuple is part of its type. So, an empty tuple is a different type than a non-empty tuple.
In fact, it doesn't even make sense to talk about "tuple" as a type. There are pairs (2-tuples aka Tuple2), triples (3-tuples aka Tuple3), quadruples, quintuples, sixtuples, septuples, octuples, 9-tuples, 10-tuples, etc, and they are all different types.
Also, more or less the only sensible thing you can do with a tuple is to extract its elements. So, for a tuple with no elements, there is pretty much no sensible thing you can do. What use is a structure that holds no values and has no operations? It's completely useless.
In fact, a 0-tuple is isomorphic to the Unit value, the value which denotes the absence of a useful value. In Scala, and also Haskell, the syntax for an empty tuple is actually used for denoting the Unit value:
val u = ()
// => u: Unit = ()
Also I am curious about is it possible with String type.
Yes, of course, you can have an empty string:
val s = ""
// => s: String = ""

Since you need to return an a value that can go wrong. In Scala the recommended way to deal with this is returning an Option, Try or Either value.
For instance:
def somethingThatCanGoWrongWithTry(): Try[(Int, String)] = {
Try{
val intValue = sideEffectValueInt()
val stringValue = sideEffectValueString()
(intValue, stringValue)
}
}
def somethingThatCanGoWrongWithOption(): Option[(Int,String)] = {
Try {
val intValue = sideEffectValueInt()
val stringValue = sideEffectValueString()
(intValue, stringValue)
}.toOption
}
def somethingThatCanGoWrongWithEither(): Either[Oops, (Int,String)] = {
Try {
val intValue = sideEffectValueInt()
val stringValue = sideEffectValueString()
(intValue, stringValue)
} match {
case Success(value) => Right(value)
case Failure(exception) => Left(Oops(exception))
}
}

Related

Check if a value either equals a string or is an an array which contains a string

A Scala map contains a key X.
The value can be either an array of Strings Array("Y")
or a simple String object, "Y".
I need to retrieve the value from the map and test
if the value is a string,
mayMap("X")=="Y"
or, if the value is an array.
myMap("X").contains("Y")
I don't want to use an if statement statement to check the type first of the value first of all. One option would be to write a function which checks the value, if it is an array then return the array, otherwise create an array with the single string element contained in the map. Then the call would be:
myToArrayFunction(myMap("X")).contains("Y")
That's what I actually do in Java.
But this is Scala. Is there a better idiom to do this in one line using pre-existing functions?
This should work:
myMap.get("X") match {
case None => println("oh snap!")
case Some(x) => x match {
case i: String => println(s"hooray for my String $i") // do something with your String here
case a: Array[String] => println(s"It's an Array $a") // do something with your Array here
}
}
case class Y(name: String)
//val a = Map[String, Any]("X" -> "Y")
val a = Map[String, Any]("X" -> Y("Peter"))
a.getOrElse("X", "Default") match {
case s: String => println(s)
case Y(name) => println(name)
}
you can also use something like this:
//val a = Map[String, Any]("X" -> "Y")
val a = Map[String, Any]("X" -> Y("Peter"))
a.map(v => println(v._2))

Retrieve tuple from string

I have the following input string:
"0.3215,Some(0.5123)"
I would like to retrieve the tuple (0.3215,Some(0.5123)) with: (BigDecimal,Option[BigDecimal]).
Here is one of the thing I tried so far:
"\\d+\\.\\d+,Some\\(\\d+\\.\\d+".r findFirstIn iData match {
case None => Map[BigDecimal, Option[BigDecimal]]()
case Some(s) => {
val oO = s.split(",Some\\(")
BigDecimal.valueOf(oO(0).toDouble) -> Option[BigDecimal](BigDecimal.valueOf(lSTmp2(1).toDouble))
}
}
Using a Map and transforming it into a tuple.
When I try directly the tuple I get an Equals or an Object.
Must miss something here...
Your code has several issues, but the big one seems to be that the case None side of the match returns a Map but the Some(s) side returns a Tuple2. Map and Tuple2 unify to their lowest-common-supertype, Equals, which is what you're seeing.
I think this is what you're trying to achieve?
val Pattern = "(\\d+\\.\\d+),Some\\((\\d+\\.\\d+)\\)".r
val s = "0.3215,Some(0.5123)"
s match {
case Pattern(a,b) => Map(BigDecimal(a) -> Some(BigDecimal(b)))
case _ => Map[BigDecimal, Option[BigDecimal]]()
}
// Map[BigDecimal,Option[BigDecimal]] = Map(0.3215 -> Some(0.5123))

Return second string if first is empty?

Here is an idiom I find myself writing.
def chooseName(nameFinder: NameFinder) = {
if(nameFinder.getReliableName.isEmpty) nameFinder.getReliableName
else nameFinder.secondBestChoice
}
In order to avoid calling getReliableName() twice on nameFinder, I add code that makes my method look less elegant.
def chooseName(nameFinder: NameFinder) = {
val reliableName = nameFinder.getReliableName()
val secondBestChoice = nameFinder.getSecondBestChoice()
if(reliableName.isEmpty) reliableName
else secondBestChoice
}
This feels dirty because I am creating an unnecessary amount of state using the vals for no reason other than to prevent a duplicate method call. Scala has taught me that whenever I feel dirty there is almost always a better way.
Is there a more elegant way to write this?
Here's two Strings, return whichever isn't empty while favoring the first
There's no need to always call getSecondBestChoice, of course. Personally, I find nothing inelegant about the code after changing that - it's clear what it does, has no mutable state. The other answers just seem overcomplicated just to avoid using a val
def chooseName(nameFinder: NameFinder) = {
val reliableName = nameFinder.getReliableName()
if(reliableName.isEmpty) reliableName
else nameFinder.getSecondBestChoice()
}
If you really want to avoid the val, here's another variant (generalises well if there are more than two alternatives)
List(nameFinder.getReliableName(), nameFinder.getSecondBestChoice()).find(_.nonEmpty).get
(or getOrElse(lastResort) if everything in the list may be empty too)
Here's a way using Option. It's not that much prettier, but everything is called only once. This assumes you want a String as a result, and don't care if the second string is empty.
Some(nameFinder.getReliableName)
.filter(_.nonEmpty)
.getOrElse(nameFinder.secondBestChoice)
Option(namefinder.getReliableName) // transforms a potential null into None
.filter(_.trim.nonEmpty) // "" is None, but also " "
.getOrElse(nameFinder.secondBestChoice)
Or better, if you can modify getReliableName to return an Option[String]:
def chooseName(nameFinder: NameFinder): String =
namefinder.getReliableName getOrElse nameFinder.secondBestChoice
Finally, if secondBestChoice can fail as well (assuming it returns an Option[String]):
def chooseName(nameFinder: NameFinder): Option[String] =
namefinder.getReliableName orElse nameFinder.secondBestChoice
If you need it more than once:
scala> implicit class `nonempty or else`(val s: String) extends AnyVal {
| def nonEmptyOrElse(other: => String) = if (s.isEmpty) other else s }
defined class nonempty
scala> "abc" nonEmptyOrElse "def"
res2: String = abc
scala> "" nonEmptyOrElse "def"
res3: String = def
Using the following pattern matching may deliver a neater scalish code,
def chooseName(nameFinder: NameFinder) = {
nameFinder.getReliableName match {
case r if r.isEmpty => r
case _ => nameFinder.secondBestChoice
}
}

Convert Scala foreach to .map

I'm new to Scala and I'm trying to convert code of the form
val series: ListBuffer[Seq[Seq[Any]]] = ListBuffer[Seq[Seq[Any]]]()
points.foreach(point => {
if( conditionA )
series += doA(...) // returns a ListBuffer[Seq[Any]]
else
series += doB(...) // returns a ListBuffer[Seq[Any]]
})
to use .map(). I'm thinking its something like:
val series: ListBuffer[Seq[Seq[Any]]] = points.map(point => {
case conditionA => doA(...)
case _ => doB(...)
})
but this doesn't compile because (I believe) the mapped sequences get appended as a single Seq[Any] instead of Seq[Seq[Any]], so I get the error
Expression of type Seq[Any] doesn't conform to expected type ListBuffer[Seq[Seq[Any]]]
Any ideas? Is there something wrong with syntax?
Let me suppose a few things, you have some function def doA(arg1: A): ListBuffer[Seq[Any]] such that you ultimately want to arrive at a List[Seq[Any]] as the final result type after mapping this function over your collection. Then what you want is flatMap instead of map:
val series = points flatMap{
case point if conditionA(point) => doA(point) result ()
case point => doB(point) result ()
}
The reason I make such a supposition is that the only reason you'd ever want to use a ListBuffer[A] in the general form is to create a List[A] through some side-effecting expression. Hence, you ultimately want a List[Seq[A]] as your final output.

How to use scalax.io.CommandLineParser?

I want to create a class that takes string array as a constructor argument and has command line option values as members vals. Something like below, but I don't understand how the Bistate works.
import scalax.data._
import scalax.io.CommandLineParser
class TestCLI(arguments: Array[String]) extends CommandLineParser {
private val opt1Option = new Flag("p", "print") with AllowAll
private val opt2Option = new Flag("o", "out") with AllowAll
private val strOption = new StringOption("v", "value") with AllowAll
private val result = parse(arguments)
// true or false
val opt1 = result(opt1Option)
val opt2 = result(opt2Option)
val str = result(strOption)
}
Here are shorter alternatives to that pattern matching to get a boolean:
val opt1 = result(opt1Option).isInstanceOf[Positive[_]]
val opt2 = result(opt2Option).posValue.isDefined
The second one is probably better. The field posValue is an Option (there's negValue as well). The method isDefined from Option tells you whether it is a Some(x) or None.
I'm not personally familiar with Scalax or Bistate in particular, but just looking at the scaladocs, it looks like a left-right disjunction. Scala's main library has a monad very much like this (Either), so I'm surprised that they didn't just use the standard one.
In essence, Bistate and Either are a bit like Option, except their "None-equivalent" can contain a value. For example, if I were writing code using Either, I might do something like this:
def div(a: Int, b: Int) = if (b != 0) Left(a / b) else Right("Divide by zero")
div(4, 2) match {
case Left(x) => println("Result: " + x)
case Right(e) => Println("Error: " + e)
}
This would print "Result: 2". In this case, we're using Either to simulate an exception. We return an instance of Left which contains the value we want, unless that value cannot be computed for some reason, in which case we return an error message wrapped up inside an instance of Right.
So if I want to assign to variable boolean value of whether flag is found I have to do like below?
val opt1 = result(opt1Option) match {
case Positive(_) => true
case Negative(_) => false
}
Isn't there a way to write this common case with less code than that?