This question already has answers here:
Checking if values in List is part of String
(2 answers)
Closed 1 year ago.
I am searching for a one line solution to check if a string contain any item from a List.
Example:
String: "This is A and B and C"
Expected Output:
If List =["A", "B] then true
If List = ["C", "D"] then true
If List = ["D", "E"] then false
I think something like Stream() in Java can solve this but I am not sure hot to use it in Scala.
You can use exists.
val str = "This is A and B and C"
val xs = List("A","C")
val res = xs.exists(s => str.contains(s))
println(res) // True
Related
In JavaScript you can join an array of strings, e.g.:
fruits = ["orange", "apple", "banana"];
joined = fruits.join(", ");
console.log(joined)
// "orange, apple, banana"
How do you do this in ReasonML?
You can use Js.Array.joinWith:
let fruits = [|"orange", "apple", "banana"|];
let joined = Js.Array.joinWith(", ", fruits);
Js.log(joined);
// "orange, apple, banana"
Converting an array to a string of joined values sounds like a job for Array.fold_left, however running
Array.fold_left((a, b) => a ++ "," ++ b, "", fruits);
produces ",orange,apple,banana".
Ideally the starting value for the fold (second argument) should the the first element in the array and the array actually used would be the rest, this avoids the initial comma. Unfortunately, this isn't easily doable with arrays, but is with lists:
let fruitList = Array.to_list(fruits);
let joined = List.fold_left((a, b) => a ++ "," ++ b, List.hd(fruitList), List.tl(fruitList));
/*joined = "orange,apple,banana"*/
Reasonml docs on lists
Here's how to implement your own join function in ReasonML:
let rec join = (char: string, list: list(string)): string => {
switch(list) {
| [] => raise(Failure("Passed an empty list"))
| [tail] => tail
| [head, ...tail] => head ++ char ++ join(char, tail)
};
};
With this, Js.log(join("$", ["a", "b", "c"])) gives you "a$b$c", much like JavaScript would.
I have a String and a Seq like :
Array[String] = Array(a, the, an)
String = "This is a sentence that includes articles a, an and the"
I want to replace each element of the Seq within the String with ""
Currently, I'm doing something like :
val a = Array("a" , "the", "an" )
var str = "This is a sentence that includes articles a, an and the"
a.foldLeft( "" ){ (x,y) => str=str.replaceAll(s"\\b${x}\\b", ""); str }
It seems to be working but doesn't look very Scala-ish mostly because of the re-assignment of the string for each iteration.
Is there any other way to do this?
This seems to be the correct variant:
a.foldLeft(str){ case (acc,item) => acc.replaceAll(s"\\b${item}\\b", "")}
It's just
a.foldLeft(str) { (x,y) => x.replaceAll(s"\\b${y}\\b", "") }
For foldLeft, x is already the intermediate result you want, no need to store it in a var.
(As a side note, your original code doesn't work correctly in general: if a is empty, it'll return "" instead of str.)
I'm a relatively new programmer learning scala and functional programming through a udemy class.
I am seeking to filter a list of strings based on another list of strings. I would like to reduce the first list down, so that when I print it out, it only contains the words - "rob", "learns", "scala"
Here's the code I am working with:
val list1:Array[String] = Array("rob","you", "to","learns", "your", "the","scala", "a")
val badWords:Array[String] = Array("you", "to", "your", "the", "a")
val list2 = list1.map(x => badWords.map(badWord => list1.filter(word => word != badWord)))
for (word <- list2) {
println(word)
}
My logic is that for each word from list1, I then try to compare each badWord element against the current list1 item to determine if it should be filtered or not.
I have run this successfully by hardcoding in what I want to have filtered, such as val list2 = list1.filter(_ != "to"). Obviously, I want give this the capability to scale, so I would like to learn how to pair the filter and map functions (if that is the correct approach).
Thanks in advance, let me know if I should provide further information or context.
You can use a very simple snippet for this:
list1.filter(!badWords.contains(_))
This will remove all the words that are also in the badWords List. Im not sure if this will work with arrays however so I suggest using Lists instead.
Example:
val words = List("Hello", "Hello", "World")
val badWords = List("Hello")
val filteredWords = words.filter(!badWords.contains(_))
I have two list.
val lis1= List("pt1","pt2","")
val lis2= List("pt1","")
I need to find the empty string in the lis1 so I am trying to do
val find= lis1.find(lis=>lis2.contains(""))
Here instead returning me "" , its returning me ("pt1"). Kindly help me how can I get empty string instead of "pt1"
It sounds like you want the intersection of the two lists. You can use filter + contains, similar to your original approach. Alternative you can use the intersect method.
val lis1 = List("pt1", "pt2", "")
val lis2 = List("pt1", "")
lis1.filter(item => lis2.contains(item))
// > res0: List[String] = List(pt1, "")
lis1.intersect(lis2)
// > res1: List[String] = List(pt1, "")
This question already has answers here:
Scala: Remove duplicates in list of objects
(10 answers)
Closed 8 years ago.
I have a class:
class Product {
val productID = ...
val weight = ...
val size = ....
.....[more fields]....
}
I have a List[Product] which contains the same product multiple times. How can I convert the list into a Set[Product] using productID as the 'unique' value so that each Product is only included once?
thanks
There is a standard way to do it:
val a = List(a1, a2...)
val as = a.toSet
If you mean that you have products with the same ID, but different, and you would be OK with picking whatever product, then you can do something like that:
val a = List(a1, a2...)
val a_ids = a map(_.productId) toSet
val products = a_ids.flatMap(id => a.find(_.productId == id))