Related
I'm new to Scala, coming over from Java, and I'm having trouble elegantly returning Map from this function. What's an elegant way to rewrite this function so it doesn't have this awful repetition?
val data = getData
if (someTest(data)) {
val D = doSomething(data)
val E = doWork(D)
if (someTest2(E)) {
val a = A()
val b = B()
Map(a -> b)
} else {
Map.empty
}
} else {
Map.empty
}
If you have a problem with connecting too many conditions with &&, you can put everything into the natural short-circuiting monad (namely Option), perform bunch of filter and map-steps on it, replace the result by Map(A() -> B()) if all the tests are successful, and then unwrap the Option with a getOrElse in the end:
Option(getData)
.filter(someTest)
.map(doSomething andThen doWork)
.filter(someTest2)
.map(_ => Map(A() -> B()))
.getOrElse(Map.empty)
In this way, you can organize your code "more vertically".
Andrey's answer is correct, but the logic can also be written using a for statement:
(for {
data <- Option(getData) if someTest(data)
d = doSomething(data)
e = doWork(d) if someTest2(e)
} yield {
Map(A() -> B())
}).getOrElse(Map.empty)
This retains a bit more of the original form of the code, but it is a matter of taste which version to use. You can also put the if on a separate line if that makes it clearer.
Note that I have retained the values of d and e on the assumption that they are actually meaningful in the real code. If not then there can be a single if expression that does all the tests, as noted in other answers:
(for {
data <- Option(getData)
if someTest(data) && someTest2(doWork(doSomething(data)))
} yield {
Map(A() -> B())
}).getOrElse(Map.empty)
You may rewrite to take advantage of short circuit, if you are mentioning to the else blocks with Map.empty as repetition.
val data = getData
if (someTest(data) && someTest2(doWork(doSomething(data)))) {
val a = A()
val b = B()
Map(a -> b)
} else {
Map.empty
}
Second solution using lazy evaluation:
val data = getData
lazy val D = doSomething(data)
lazy val E = doWork(D)
if (someTest(data) && someTest2(E)) {
val a = A()
val b = B()
Map(a -> b)
} else {
Map.empty
}
D, E and someTest2(E) won't get evaluated if someTest(data) is false.
I would like to simplify this:
var countA: Int = 0
var countB: Int = 0
if (validItem) {
if (region.equalsIgnoreCase( "US" )) {
if (itemList > 0) {
countB = 1
} else {
countA = 1
}
} else {
countB = 1
}
} else {
countA = 1
}
How do I use ternary operator in scala.
You should not need to use a ternary operator in Scala. In Scala, if is an expression not a statement, you can say val x = if (b) 1 else 2.
The usage of var in your example also points to a problem, because you can usually avoid this when you use the if as an expression.
Let's try to break down the code to avoid the var, i.e. first remove all if statements that are not expressions with a corresponding else and always provide both values:
var countA: Int = ???
var countB: Int = ???
if (validItem) {
if (region.equalsIgnoreCase("US")) {
if (itemList > 0) {
countA = 0
countB = 1
} else {
countA = 1
countB = 0
}
} else {
countA = 0
countB = 1
}
} else {
countA = 1
countB = 0
}
Now we can define the condition for which either of countA and countB is one:
val isUS = region.equalsIgnoreCase("US")
val hasItems = itemList > 0
val isA = !validItem || (isUS && !hasItems)
val isB = !isA
// or: val isB = validItem && (!isUS || hasItems)
and then:
val countA = if (isA) 1 else 0
val countB = if (isB) 1 else 0
I think the short answer is that in Scala there is no ?: ternary operator. Although you can imitate the syntax using implicits (see #jwvh's answer), I think it doesn't really simplify anything.
There are a couple of important properties of the conventional ?:
it always has two branches
following from the previous property, the ternary operator always returns a value (this is mostly the point of using ?:)
val result: Int = if (true) 1 else 2
// result is 1
branches are evaluated lazily
if (true) 1 else (0/0) // returns 1
if (false) 0/0 else 2 // returns 2
// i.e. 0/0 is not evaluated
As you see, in Scala if-else (with else) construction satisfies these properties. This is not the case for if-else construction in some other languages, like C or Java, because it doesn't return a value.
So the bottom line is that in Scala you don't need a ternary operator, because you can just use if-else.
UPDATE
As Alexey Romanov mentions in the comments, if statement without else actually satisfies the first condition as well. When you write
val result = if (true) 1
it actually means if (true) 1 else (), so result will have type AnyVal instead of Int, because the return type of the if expression is the lowest common bound of the both branches (Int and Unit in this case).
This might be a bit confusing for a "newbie", but you could attach a ternary method to the Boolean class like so.
implicit class Ternary[T](condition: Boolean) {
def ??(a: => T, b: => T): T = if (condition) a else b
}
Usage:
(4 == 4)??("yes","no") // res0: String = yes
("abc".length < 2).??(1,0) // res1: Int = 0
List('c').isEmpty.??('X','+') // res2: Char = +
To expand on #0__'s answer (if that is his/her real name), you can also use tuples to assign to two variables at once.
val (countA, countB) =
if (validItem) {
if (region.equalsIgnoreCase("US")) {
if (itemList > 0) (0,1) else (1,0)
} else {
(0,1)
}
} else {
(1,0)
}
This is an old question and I'm taking a break from a current problem, so I thought I'd leave a basic pattern match solution.
val (countA, countB) =
(validItem, region.equalsIgnoreCase("US"), itemList > 0) match {
case (true, true, false) | (false, _, _) => (1, 0)
case _ => (0, 1)
}
I wrote sum code in scala to find the majority element(the element which appears more than n/2 times where 'n' is the no.of elements in an array.I want to know where there is functional / scala native style of version(which includes match cases and transformations like "map/"flatmap" etc..) for the below imperative style of scala code which includes looping. The code which i used in:
object MajorityElement{
def printMajority(arr:Array[Int]) ={
var cand:Int=findCandidate(arr);
if(isMajority(arr,cand))
println(cand);
else
println("No Majority Element");
}
def isMajority(arr:Array[Int],Cand:Int):Boolean ={
var count=0;
for(i <- 0 until arr.length){
if(arr(i)== Cand)
count+=1;
}
if (count > arr.size/2)
return true;
else false
}
def findCandidate(arr:Array[Int]):Int ={
val s = arr.size
var majIndex:Int = 0;
var count = 1;
for(i <- 0 until arr.length){
if(arr(majIndex) == arr(i))
count+=1;
else
count-=1;
if(count==0)
{
majIndex = i;
count =1
}
}
return arr(majIndex);
}
}
please let me know, whether it is possible to write/ convert imperative style to functional version in scala(which uses match cases) for any scenario.
If you're only interested in the final result (and so you don't need isMajority etc), it's very simple
def findMajority(xs: List[Int]) = {
val mostFrequent = xs.groupBy(identity).values.maxBy(_.length)
if (mostFrequent.length >= xs.length / 2) Some(mostFrequent.head) else None
}
findMajority(List(1, 2, 2, 2, 3, 3, 3, 3, 3, 4))
//Option[Int] = Some(3)
Group equal elements into lists (the values of the Map returned by GroupBy). Pick the longest list. If its length is more than half the list, then it's a majority, return Some(the head) (any element will do, they're all the same value). Otherwise, return None
The transition from imperative thinking to functional thinking takes time and study. One approach is to find code examples here on SO and, with the help of the Standard Library, break it down until you understand what's going on.
Here's a little something to get you started.
def isMajority(arr:Array[Int],cand:Int):Boolean =
arr.count(_ == cand) > arr.size/2
Threr is no Native Scala Style, but code can be Functional Style(value oriented)
(No var, No Side-Effect, Pure Function)
object MajorityElement {
case class Candidate(idx: Int, count: Int)
def solve(arr: Array[Int]): Option[Int] = {
val candidate = findCandidate(arr)
if (isMajority(arr, candidate)) Option(arr(candidate.idx))
else None
}
def isMajority(arr: Array[Int], candidate: Candidate) =
arr.count(_ == arr(candidate.idx)) > arr.size / 2
def findCandidate(arr: Array[Int]): Candidate =
arr.indices.foldLeft(Candidate(0, 1)) { (acc, idx) =>
val newAcc =
if (arr(acc.idx) == arr(idx)) acc.copy(count = acc.count + 1)
else acc.copy(count = acc.count - 1)
if (newAcc.count == 0) Candidate(idx, 1)
else newAcc
}
}
val arr = Array(1, 1, 1, 2, 3, 4, 1)
val ret = MajorityElement.solve(arr)
ret match {
case Some(n) => println(s"Found Majority Element: $n")
case None => println("No Majority Element")
}
Much like this question:
Functional code for looping with early exit
Say the code is
def findFirst[T](objects: List[T]):T = {
for (obj <- objects) {
if (expensiveFunc(obj) != null) return /*???*/ Some(obj)
}
None
}
How to yield a single element from a for loop like this in scala?
I do not want to use find, as proposed in the original question, i am curious about if and how it could be implemented using the for loop.
* UPDATE *
First, thanks for all the comments, but i guess i was not clear in the question. I am shooting for something like this:
val seven = for {
x <- 1 to 10
if x == 7
} return x
And that does not compile. The two errors are:
- return outside method definition
- method main has return statement; needs result type
I know find() would be better in this case, i am just learning and exploring the language. And in a more complex case with several iterators, i think finding with for can actually be usefull.
Thanks commenters, i'll start a bounty to make up for the bad posing of the question :)
If you want to use a for loop, which uses a nicer syntax than chained invocations of .find, .filter, etc., there is a neat trick. Instead of iterating over strict collections like list, iterate over lazy ones like iterators or streams. If you're starting with a strict collection, make it lazy with, e.g. .toIterator.
Let's see an example.
First let's define a "noisy" int, that will show us when it is invoked
def noisyInt(i : Int) = () => { println("Getting %d!".format(i)); i }
Now let's fill a list with some of these:
val l = List(1, 2, 3, 4).map(noisyInt)
We want to look for the first element which is even.
val r1 = for(e <- l; val v = e() ; if v % 2 == 0) yield v
The above line results in:
Getting 1!
Getting 2!
Getting 3!
Getting 4!
r1: List[Int] = List(2, 4)
...meaning that all elements were accessed. That makes sense, given that the resulting list contains all even numbers. Let's iterate over an iterator this time:
val r2 = (for(e <- l.toIterator; val v = e() ; if v % 2 == 0) yield v)
This results in:
Getting 1!
Getting 2!
r2: Iterator[Int] = non-empty iterator
Notice that the loop was executed only up to the point were it could figure out whether the result was an empty or non-empty iterator.
To get the first result, you can now simply call r2.next.
If you want a result of an Option type, use:
if(r2.hasNext) Some(r2.next) else None
Edit Your second example in this encoding is just:
val seven = (for {
x <- (1 to 10).toIterator
if x == 7
} yield x).next
...of course, you should be sure that there is always at least a solution if you're going to use .next. Alternatively, use headOption, defined for all Traversables, to get an Option[Int].
You can turn your list into a stream, so that any filters that the for-loop contains are only evaluated on-demand. However, yielding from the stream will always return a stream, and what you want is I suppose an option, so, as a final step you can check whether the resulting stream has at least one element, and return its head as a option. The headOption function does exactly that.
def findFirst[T](objects: List[T], expensiveFunc: T => Boolean): Option[T] =
(for (obj <- objects.toStream if expensiveFunc(obj)) yield obj).headOption
Why not do exactly what you sketched above, that is, return from the loop early? If you are interested in what Scala actually does under the hood, run your code with -print. Scala desugares the loop into a foreach and then uses an exception to leave the foreach prematurely.
So what you are trying to do is to break out a loop after your condition is satisfied. Answer here might be what you are looking for. How do I break out of a loop in Scala?.
Overall, for comprehension in Scala is translated into map, flatmap and filter operations. So it will not be possible to break out of these functions unless you throw an exception.
If you are wondering, this is how find is implemented in LineerSeqOptimized.scala; which List inherits
override /*IterableLike*/
def find(p: A => Boolean): Option[A] = {
var these = this
while (!these.isEmpty) {
if (p(these.head)) return Some(these.head)
these = these.tail
}
None
}
This is a horrible hack. But it would get you the result you wished for.
Idiomatically you'd use a Stream or View and just compute the parts you need.
def findFirst[T](objects: List[T]): T = {
def expensiveFunc(o : T) = // unclear what should be returned here
case class MissusedException(val data: T) extends Exception
try {
(for (obj <- objects) {
if (expensiveFunc(obj) != null) throw new MissusedException(obj)
})
objects.head // T must be returned from loop, dummy
} catch {
case MissusedException(obj) => obj
}
}
Why not something like
object Main {
def main(args: Array[String]): Unit = {
val seven = (for (
x <- 1 to 10
if x == 7
) yield x).headOption
}
}
Variable seven will be an Option holding Some(value) if value satisfies condition
I hope to help you.
I think ... no 'return' impl.
object TakeWhileLoop extends App {
println("first non-null: " + func(Seq(null, null, "x", "y", "z")))
def func[T](seq: Seq[T]): T = if (seq.isEmpty) null.asInstanceOf[T] else
seq(seq.takeWhile(_ == null).size)
}
object OptionLoop extends App {
println("first non-null: " + func(Seq(null, null, "x", "y", "z")))
def func[T](seq: Seq[T], index: Int = 0): T = if (seq.isEmpty) null.asInstanceOf[T] else
Option(seq(index)) getOrElse func(seq, index + 1)
}
object WhileLoop extends App {
println("first non-null: " + func(Seq(null, null, "x", "y", "z")))
def func[T](seq: Seq[T]): T = if (seq.isEmpty) null.asInstanceOf[T] else {
var i = 0
def obj = seq(i)
while (obj == null)
i += 1
obj
}
}
objects iterator filter { obj => (expensiveFunc(obj) != null } next
The trick is to get some lazy evaluated view on the colelction, either an iterator or a Stream, or objects.view. The filter will only execute as far as needed.
How can I initialize a val that is to be used in another scope? In the example below, I am forced to make myOptimizedList as a var, since it is initialized in the if (iteration == 5){} scope and used in the if (iteration > 5){} scope.
val myList:A = List(...)
var myOptimizedList:A = null
for (iteration <- 1 to 100) {
if (iteration < 5) {
process(myList)
} else if (iteration == 5)
myOptimizedList = optimize(myList)
}
if (iteration > 5) {
process(myOptimizedList)
}
}
This may have been asked before, but I wonder if there is an elegant solution that uses Option[A].
Seems that you have taken this code example out of the context, so this solution can be not very suitable for your real context, but you can use foldLeft in order to simplify it:
val myOptimizedList = (1 to 100).foldLeft (myList) {
case (list, 5) => optimize(list)
case (list, _) => process(list); list
}
You can almost always rewrite some sort of looping construct as a (tail) recursive function:
#annotation.tailrec def processLists(xs: List[A], start: Int, stop: Int) {
val next = start + 1
if (start < 5) { process(xs); processLists(xs, next, stop)
else if (start == 5) { processLists( optimize(xs), next, stop) }
else if (start <= stop) { process(xs); processLists( xs, next, stop ) }
}
processLists(myList, 100, 1)
Here, you pass forward that data which you would otherwise have mutated. If you need to mutate a huge number of things it becomes unwieldy, but for one or two it is often as clear or clearer than doing the mutation.
It's often the case that you can rework your code to avoid the problem. Consider the simple, and common, example here:
var x = 0
if(something)
x = 5
else
x = 6
println(x)
This would be a pretty common pattern in most languages, but Scala has a better way of doing it. Specifically, if-statements can return values, so the better way is:
val x =
if(something)
5
else
6
println(x)
So we can make x a val after all.
Now, clearly your code can be rewritten to use all vals:
val myList:A = List(...)
for (iteration <- 1 to 5)
process(myList)
val myOptimizedList = optimize(myList)
for (iteration <- 5 to 100)
process(myOptimizedList)
But I suspect this is simply an example, not your real case. But if you're unsure how you might rearrange your real code to accomplish something similar, please show us what it looks like.
There's another technique (perhaps trick in this case) to delay initialization of
myOptimizedList which is to use a lazy val. Your example is very specific but the principal is still obvious, delay assignment of a val until it is first referenced.
val myList = List(A(), A(), A())
lazy val myOptimizedList = optimize(myList)
for (iteration <- 1 to 100) {
if (iteration < 5)
process(myList)
else if (iteration > 5)
process(myOptimizedList)
}
Note that the case iteration == 5 is ignored.