I have a list as such:
myList: ("ab";"bc";"cd","de");
I would like to get a sublist like that contains "b"
I know i can do this:
myList like "*b*"
However this returns a binary list. 1100b;
How can I return a list of ("ab";"bc") instead?
Following code returns needed sublist
myList: ("ab";"bc";"cd","de");
myList where myList like "*b*"
As you have mentioned
myList like "*b*" returns boolean list 1100
where 1100 returns list of indices with true value: 0, 1
myList 0 1 returns first two elements of myList
Related
Most likely easy problem but I can't find a way out:
I have a function go(a,b,c): List
and another List list1 that I'm iterating
val result = List[]()
for(t<- list1){ result = result ::: go(a,b,t)}
Now obviously this does not work because val is immutable but is there a way to return a List like this?
Learning Scala right now to prepare for college
I want to add a list into another list at a certain index without replacing elements at that index. For instance, if I have an initial list:
var list1: List[Int] = List(1,2,3,4)
I want to add List(4,1,5) into it so that it will become:
var list1: List[Int] = List(1,2,4,1,5,3,4)
Edit: I've tried creating new lists and adding the head of the first list, the list I want to add to the first, and the tail of the first list to return a brand new list.
This is what I did but I was wondering if there were any more efficient and "smarter" ways. I've done some research on insert but I'm not sure if insert satisfies what I'm trying to do as I don't understand insert fully.
A key part of learning Scala is learning the standard library, which has a rich set of classes and methods to handle a lot of standard operations. In this case the splitAt method on a collection is going to help:
var list1 = List(1, 2, 3, 4)
val list2 = List(4, 1, 5)
val (pre, post) = list1.splitAt(2)
pre ++ list2 ++ post
This is a "smart" way of doing it because it clearly and simply shows the sequence of operations that is being done, making the code easier to write and easier to maintain.
Note that this is safe in the case where the initial list is shorter than 2 elements because splitAt takes care of this and just returns the initial list in pre and leaves post empty.
Scala collections have a patch member, which can replace or insert elements:
var list1 = List(1,2,3,4)
list1.patch(2, List(4,1,5), 0)
Note: inserting elements is done by telling the collection to replace 0 elements.
def insertlistAtIndex(index : Int , original : List[Int], appendedList : List[Int]) : List[Int] = {
original.
zipWithIndex.flatMap{case (elem, ind) =>
if(ind == index)
appendedList :+ elem // append the element at that index
// appendedList ::: List(elem) more efficient solution (concatenation)
else
List(elem)
}
}
val list1: List[Int] = List(1,2,3,4)
val list2 : List[Int] = List(4,1,5)
val expectedResult : List[Int] = List(1,2,4,1,5,3,4)
val insertAtIndex = 2
assert(insertlistAtIndex(insertAtIndex,list1,list2) == expectedResult )
Here is another solution, it's more flexible and functional, the idea is to zip the list with its index, move through each element in the list, and when you arrive at the index you want to put the other list, you insert that list there, as well as the element that was originally at that element(shown in two ways). This way, you avoid unnecessary exceptions even if the index supplied is out of range. Hope this helps.
As lists are immutable I see that there is no remove index command in scala, like this:
// to remove value 3
val list List() = 3 :: 4 :: 5 :: Nil
list.remove(list.head)
// to remove value 5
list.remove(list.size)
Is it possible to create a list like:
// before: list(3,4,5)
val newList = list.listFromRange(2,3) // like substring command
// after: newList(4,5)
Would it be feasibile or even possible to create a string for the list and then substring the number? Only issue with this is that if the list contained elements of varying lengths, such as:
exampleList: 1,2,10,25,3,4
val newList = exampleList.toString.subString(4, 6)
// desired value: newList(25,3)
// actual value: newList(0,2)
The Standard Library has lots going for it. Take some time to study it. It's worth the effort.
List(3,4,5).diff(Range(2,4))
//res0: List[Int] = List(4, 5)
List(1,2,10,25,3,4).slice(3,5)
//res1: List[Int] = List(25, 3)
Code:
object Permutations extends App
{
val ar=Array(1,2,3).combinations(2).foreach(println(_))
}
Output:
[I#378fd1ac
[I#49097b5d
[I#6e2c634b
I am trying to execute this but I am getting some other values.
How to print array values in Scala? Can any one help to print?
Use mkString
object Permutations extends App {
Array(1,2,3).combinations(2).foreach(x => println(x.mkString(", ")))
}
Scala REPL
scala> Array(1,2,3).combinations(2).foreach(x => println(x.mkString(", ")))
1, 2
1, 3
2, 3
When array instance is directly used for inside println. The toString method of array gets called and results in output like [I#49097b5d. So, use mkString for converting array instance to string.
Scala REPL
scala> println(Array(1, 2))
[I#2aadeb31
scala> Array(1, 2).mkString
res12: String = 12
scala> Array(1, 2).mkString(" ")
res13: String = 1 2
scala>
You can't print array directly, If you will try to print it will print the reference of that array.
You are almost there, Just iterate over array of array and then on individual array and display the elements like below
Array(1,2,3).combinations(2).foreach(_.foreach(println))
Or Just convert each array to string and display like below
Array(1,2,3).combinations(2).foreach(x=>println(x.mkString(" ")))
I hope this will help you
if am trying to write a simple function that list of pair of integers - representing a graph and returns a list of integers : all the nodes in a graph
eg if input is [(1,2) (3,4) (5,6) (1,5)]
o/p should be [1,2,3,4,5,6,1,5]
The function is simply returning list of nodes , in the returning list values may repeat as above.
I wrote the following function
fun listofnodes ((x:int,y:int)::xs) = if xs=nil then [x::y] else [[x::y]#listofnodes(xs)]
stdIn:15.12-15.18 Error: operator and operand don't agree [tycon mismatch
operator domain: int * int list
operand: int * int
in expression:
x :: y.
I am not able to figure out what is wrong.
first of all you should know what each operator does:
:: puts individual elemtents into an existing list so that: 1::2::3::[] = [1,2,3]
# puts two lists together so that: [1,2] # [3,4] = [1,2,3,4]
you can also use :: to put lists together but then it becomes a list of lists like:
[1,2] :: [3,4] = [[1,2],[3,4]]
so by writing [x::y] you are saying that x and y should become a list inside a list.
and you shouldnt use an if statement to check for the end of the list, instead you can use patterns to do it like this:
fun listofnodes [] = []
| listofnodes ((x,y)::xs) = x :: y :: listofnodes(xs);
the first pattern assures that when we reach the end of the list, when you extract the final tuple your xs is bound to an empty list which it calls itself with, it leaves an empty list to put all the elements into, so that [(1,2) (3,4) (5,6) (1,5)] would evaluate like this:
1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 1 :: 5 :: [] = [1,2,3,4,5,6,1,5].
you could also make it like this:
fun listofnodes [] = []
| listofnodes ((x,y)::xs) = [x,y] # listofnodes(xs);
this way you make a small 2 element list out of each tuple, and then merge all these small lists into one big list. you dont really need the empty list at the end, but its the only way of ensuring that the recursion stops at the end of the list and you have to put something on the other side of the equals sign. it evaluates like this:
[1,2] # [3,4] # [5,6] # [1,5] # [] = [1,2,3,4,5,6,1,5].
also you cast your x and y as ints, but you dont really have to. if you dont, it gets the types " ('a * 'a) list -> 'a list " which just means that it works for all input types including ints (as long as the tuple doesnt contain conflicting types, like a char and an int).
im guessing you know this, but in case you dont: what you call pairs, (1,2), is called tuples.