How do you push a string into a List? [closed] - scala

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.)

Related

How can i count occurrences in a list using this function in scala [closed]

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.

Query on scala Collections [closed]

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")

Add a number to every element in an Array[Double] [closed]

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.

scala type mismatch in map function [closed]

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
Newbie to Scala.
I encountered this error while compile the code.
Error:(84, 130) type mismatch;
found : String
required: Array[String]
val mappingStr = "Mapping Strings: \n" + stringIndexers.map(r=>Array(r.getInputCol, r.labels.mkString(", "))).reduce(_+"\n"+_.mkString(": \n")) + "\n"
^
the hat char points at "Array" of my code.
I didn`t see any issue, can anyone help to explain why?
You map a list of some items into a list of Array[String], because it's what Array() apparently returns for each element of stringIndexers.
Then you try to reduce this List[Array[String]] by +-ing Strings. This expects _ in reduce to be a String, but it is not, it's an Array[String].
You should provide a way to convert your arrays into strings, or maybe flatten your list of arrays first, it's hard for me to tell which your intention is.

join two sequences in scala [closed]

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 8 years ago.
Improve this question
This is rewritten question. Previous one is unclear.
1) Introduction
I need some cool structure, that would store my values. I need that my cool structure can add items to it, and sometimes I need that my cool structure can fold containing elements into something based on passed foldFunction . Generally something like scala.collection.immutable.List is great, besides point 2.
See this in action:
val coolContainer = 1 :: 2 :: 3 :: 4 :: Nil
val folded = coolContainer.foldLeft("")((acc, curr)=> acc + curr)
Yea! I got what I wanted - the shiny "1234" String :)
2) Additional requirements
Then I want that my cool structure can be appended to another one. More over this is very important that such operation must be efficient because my program will mostly do such operations. Because of that, the "appending of two containers" algorithm with complexity O(1) is very expected.
So, lets just try to append two Lists, one to another using standard way with the ++ function.
val locomotive = (1 to 1000000).toList
val vehicle = (1000000 to 2000000).toList
val train = locomotive ++ vehicle
So what is going here? As most of you probably know, the List in Scala Standard Library API is implemented as head prepended to tail where tail is another List. Finally the last element in list is prepended to empty List Nil.
This architecture implies that if you join two lists using the ++ function, algoirithm under the hood will traverse locomotive through all elements until the last item and then replace the tail (which is the Nil) with the value of another List - with the vehicle in our example. The complexity is O(size_of_loclomotive). Ehh, :/ I want it to be O(1).
Finally the question.
Is there in scala container, that behaves similarly to the List and meets the above requirements?
Deprecated, old question. Just in case if you are just interested how it was reasked and don't.
Basically I want to choose the best pair: structure and method for appending one sequence to another. The efficiency is the key in this scenario.
Read below snipped to understand what I want to achieve but more efficient:
val seq1 = List(1,2,3)
val seq2 = List(4,5,6)
val seq3 = seq1 ++ seq2 //I am afraid that seq1 and seq2 will be traversed
//what is not the most efficient way to join two seqs
If you're going to be appending over and over, where eventually the prepended list is going to be much bigger than the appended, your best bet for an immutable data structure is Vector. If the lists are all really short, though, it's hard to beat just plain List; yes, you have to allocate three extra objects but the overhead for Vector is much more.
Keep in mind, though that you can prepend and reverse (with a List), and that there are mutable data structures that support an efficient append (e.g. ArrayBuffer, or perhaps ListBuffer if you want to convert to a list when you're done appending).
Appending is O(n), for constant time appending you can use a ListBuffer and call toList when you want the immutable list.