Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have the following:
var x = some array Array[Double]
val n = 3
I want to add n to every element in x, how? I tried:
x.map(v => v + n)
But that doesnt work.
You have to use a third var like this :
val x2 = x.map(_ + n)
If you don't want to construct a new Array but just want to modify the values in the existing one, then:
for (i <- x.indices)
x(i) += n
In general, the Scala collections API doesn't currently offer higher-level operations that do in-place mutation, so you have to resort to lower-level code like this. (That will change in Scala 2.13.)
You will have to write the return output of map into a variable to get the updated array.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I've found multiple ways of doing this already but haven't been able to apply those here since i'm not familiar with the language yet, so maybe a more direct question could help
def occurrences(cars: List[Char]): List [(Char, Int)] = {
. . .
}
Thanks in advance!
If you are not familiar with the language, this answer will probably not help you very much ... but then, it's not very likely that another will. My advice to you would be to grab a book and learn the basics of the language first, before jumping into asking other people to solve random made up problems for you.
As to counting characters in a string, it would be something like this:
chars.groupBy(identity).mapValues(_.size).toList
As both answers here show, there are plenty of ways to solve this using the stdlib; as I always say the Scaladoc is your friend.
Also, as both answers suggest, it is recommended that you learn the language.
However, I wanted to show another cool way of solving this problem using cats.
import cats.syntax.all._
chars.foldMap(char => Map(char -> 1))
foldMap is a function added by cats to the List[Char] that as the name suggests does mapping and folding in the same step.
The folding is done using the default combine operation of the type returned by the map. And the default combine operation of a Map is to join both maps and combine values with matching keys using their default combine operation; and for ints that is sum.
First of all, cars is not a good name for a list of characters :) (I know, just kidding). You should definitely get more into the language and read more about some of the most used functions, like what they are, what they do and why they exist, but just to answer this specific question, you can do this:
Approach No.1:
def occurrences(chars: List[Char]): List[(Char, Int)] =
chars.foldLeft(Map.empty[Char, Int])(
(occurrencesMap, newChar) => occurrencesMap.updatedWith(newChar) {
case Some(count) => Some(count + 1)
case None => Some(1)
}
).toList
Explanation:
Basically we're just iterating over the list, and we want to aggregate the data in a structure, where a character is mapped to its number of usages, so we use a Map[Char, Int], and during the iteration, if the aggregator (occurrencesMap in this case) contains the char, we increment it and otherwise we initiate it with 1.
Approach No.2:
I can also suggest this one-line approach, but I think the first approach is more beginner-friendly or understandable in some senses:
def occurrences(chars: List[Char]): List[(Char, Int)] =
chars.groupMapReduce[Char, Int](identity)(_ => 1)(_ + _).toList
Explanation:
As the function name declares groupMapReduce first groups the values inside the list by a function, then maps each key occurrence into a value, and then reduce the resulted values for each key, into a single item, so we use identity to group the items inside the list, by the value of the character itself, and if a character is found, we basically just found 1 character right? so ignore the value of the character, and just return 1 :D _ => 1, and at the end, you would have something like 'c' -> List(1, 1, 1), so let's just add them all together, or use .length to count the occurrences.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
i'm extremely new to swift but i have previous experience through college in other programming languages so im familiar with the logistics. however my college professor asked us to do something rather weird that i would have used an Array for, and without one i have no clue how to do what he is asking.
The question is as states:
Create a closure that accepts two Ints and returns an Int (the sum of both int's provided)
but to retrieve the sum, you are supposed to use a For-In Loop?
any help or even a push in the right direction would be greatly appreciated.
my current code to solve this issue is something extremely simple.
var returnSum = { (a: Int, b: Int) -> Int in
var sum: Int
sum = (one + two)
return sum
}
But i feel like if i hand that in im going to be getting a one very bad mark.
Thank you!
The code can simply be written as,
var returnSum = { $0 + $1 }
And since there is nothing sequence like here, a loop makes no sense.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
is there any way to get distinct elements by comparing below two sequences only considering 2nd and 3rd arguments of Person element
case class Person(i:Long,name:String,uname2:String,uname:String)
val firstSeq = Seq(Person(null,"aaa","bbb",null),Person(null,"bbb","ccc",null))
val secondSeq = Seq(Person(123456,"aaa","bbb","Bob"),Person(2345678,"ccc","bbb","John"),
Person(34567890,"bbb","ccc","Mike"))
Excepting result from firstSeq perceptive after comparsion Seq(Person(null,"bbb","ccc",null))
Excepting result from secondSeq perceptive after comparsion Seq(Person(2345678,"ccc","bbb","John"))
The question is not that clear, but this code removes elements from two lists where they share the same values of name and uname2, or where there is no corresponding value in the other list.
val (r1, r2) = firstSeq.zip(secondSeq).filterNot {
case (a, b) => a.name == b.name && a.uname2 == b.uname2
}.unzip
Also note that it is much safer to use Option[Int] and Option[String] rather using null to indicate missing values.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to make a chatbox in scala. When a user will type anything, I want to stack those in a list.
But when I tried to do list += message
It's saying list is a list of string , and messgae is a string. So, it's not adding the string in the list actually.
Is there anyway to push the string in the list? Like in python u can do append??
You have two choices.
A mutable ListBuffer[String] ...
val ml = collection.mutable.ListBuffer("one","six")
ml += "ten" //res0: ml.type = ListBuffer(one, six, ten)
... or an immutable List[String] referenced via a mutable variable.
var il = List("two","four")
il = il :+ "five" //il: List[String] = List(two, four, five)
(You could combine them, a mutable variable holding a mutable collection, but that's a bad idea X 2.)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Both tuples and list are accepting the different type values as attached in snippet, then what is the main difference?
Scala is a typed language. You want your program to know as much as possible about the shape of the data it is working with.
List[Any] is not a very useful type. It does not tell you that there are three elements in there, and what their respective types are.
(Int, Double, String) tells you much more.
Lists are for collections of elements of all the same type (but unknown number).
Tuples are for the combination of a fixed number of elements (that can each have their own type).
Tuples can also be seen as ad-hoc versions of case classes (which you have to define first, but then give you named fields, and methods and all that):
val myData = FooDataRecord(id = 1, amount = 1.1, name = "a")