let's say I have a list defined in Kotlin:
val mylist = mutableListOf<List<Int>>(listOf(2,3,5), listOf(2,5,6))
Now, I want to assign a certain value to one of these sublists. For example, now that I have a list of
((2,3,5)(2,5,6))
I would like my list to be
((2,3,5)(2,100,6))
I'm used to doing this in Python by something like myList[1][1] = 100. How do I achieve the same result in Kotlin?
Kotlin has two sets of collection interfaces, the regular List, Set, etc. which are read-only, and the same ones with the Mutable prefix, which can be modified.
listOf will give you a List instance, while mutableListOf gives you a MutableList instance. If you use the latter for creating your nested lists, you can use the exact syntax you've asked about:
val mylist: MutableList<MutableList<Int>> = mutableListOf(mutableListOf(2,3,5), mutableListOf(2,5,6))
mylist[1][1] = 100
println(mylist) // [[2, 3, 5], [2, 100, 6]]
(I've added the explicit type for myList for clarity's sake, it can be omitted from the left side of the assignment.)
Related
I am trying to write a function in SML that takes in a pair of lists. The first list in the pair is a list of integers and the second list is a list of booleans. Ex: (([3, 5, 9], [true, false, false])). I am having trouble with the proper syntax to return how many times 'true' is found in the second list.
You would want to break this down.
Can you count the number of times a value is found in a list?
Can you pattern match out the second list in the tuple?
The first one can be accomplished by implementing a count function. A basic shell for that would look something like:
fun count (_, []) = ...
| count (v, (x::xs)) =
if ... then ...
else ...
For the second, well, you can see pattern-matching for binding names to the elements of a tuple in the above code.
Doing anything more would be doing your homework for you, and that would be a disservice.
I have a list of tuples in the following format
[{"string1",1},{"string2",2}...]
I'm gonna use that for another function but i realized i can't have that or rather i just think is too difficult to operate over that list in that format, so my solution was transforming that list into the following
["string1", "string2",...]
But i'm not sure how to do this as i'm still learning how Elixir works.
My way of getting it was this:
for x <- words do
text ++ elem(words,0)
end
"text" being an empty list and "words" being the list of tuples. But of course this doesn't work, not really sure why.
If you want to do it using for, you need to understand that for is not a construct to iterate over things, as in other programming languages. In Elixir, for is used for comprehensions, meaning that the result will be a data structure, created from an enumerable, like your list of tuples.
You also need to understand that if you updated your code, text ++ elem(words, 0) wouldn't actually update text, and that ++ doesn't work the way you think it does either. ++ is useful for concatenating lists, or keyword lists, but not for adding single elements to a list. For that purpose you could do list ++ ["string"] or ["string"] ++ list which is faster; or even simpler: ["string" | list].
And the reason it wouldn't update your list, is that in each "iteration" you would just be producing the concatenation, but you wouldn't actually be assigning that anywhere. And things in Elixir are not mutable, so ++ doesn't actually update something
Now, in order to correctly create what you want using for, you could do it like this:
iex> list = [{"string1", 1}, {"string2", 2}]
[{"string1", 1}, {"string2", 2}]
iex> for tup <- list, do: elem(tup, 0)
["string1", "string2"]
iex> for {string, _} <- list, do: string
["string1", "string2"]
Which basically means: using this list, create a new one, keeping only the first element of each tuple. Since a list is the default output of for. But you could also change the resulting data structure adding into: %{} or something else. Comprehensions are very powerful, you can get a better understanding of them here
Another popular way to solve it would be using Enum.map, which maps a given enumerable to something else. Meaning that it transforms the elements of the enumerable, so you could do it like this as well:
iex> list = [{"string1", 1}, {"string2", 2}]
[{"string1", 1}, {"string2", 2}]
iex> Enum.map(list, fn {string, _} -> string end)
["string1", "string2"]
Here, the transformation would be made by the function which takes the tuple, matching the first element into something called string and "returns" just that for each element.
Another simple way you could to it is using Enum.unzip/1 which takes a list of two-element tuples, like the ones you have, and produces a tuple with two elements. The first one being a list with the first element from each of your tuples, and the second one, a list with the second element from each of your tuples.
So, you could do:
iex> list = [{"string1",1},{"string2",2}]
[{"string1", 1}, {"string2", 2}]
iex> {strings, _} = Enum.unzip(list)
{["string1", "string2"], [1, 2]}
iex> strings
["string1", "string2"]
This way, you would be left with a strings variable, containing the list you want. However, this only works with two element tuples, so if you have any tuple that has more than two, it wouldn't work. Besides, you wouldn't be using the second list, so the for comprehension here could suit you better.
The most simple way to solve this is just using Enum.map https://hexdocs.pm/elixir/Enum.html#map/2
[{"string1", 1}, {"string2", 2}]
|> Enum.map(fn { string, _ } -> string)
To learn Elixir just keep doing what you are doing and look into the Docs and keep asking here as well
How do I append an element to the beginning of a list in Prolog? I need the end result to be called like so:
pushFront(8, [3, 1], NewList). % NewList is now [8, 3, 1].
I have tried to implement it as follows:
pushFront(Item, [], [Item|_]). %Problematic
pushFront(Item, [OldDequeH|OldDequeT], NewDeque) :-
leftPush(OldDequeH, OldDequeT, [Item|NewDeque]).
But it does not work, and I'm out of ideas tbh. Can anyone describe what is wrong with my implementation and what changes it needs to work properly?
To add an element at the beginning of a list, just use list notation:
pushFront(Item, List, [Item|List]).
The list representation uses internally the cons functor (.), so a list [b,c,d] is just syntactic sugar for '.'(b,'.'(c, '.'(d, []))).
This representation allows you to add an item at the front just by wrapping another cons functor, i.e. if you want to a add an item a at the front of a list L you would wrap a '.'(a, L), which we usually write simply as [a|L].
I have two lists in python.
a=[1,4,5]
b=[4,1,5]
What i need is to order b according to a. Is there any methods to do it so simply without any
loops?
The easiest way to do this would be to use zip to combine the elements of the two lists into tuples:
a, b = zip(*sorted(zip(a, b)))
sorted will compare the tuples by their first element (the element from a) first; zip(*...) will "unzip" the sorted list.
or may be just check everything is perfect then..copy list a for b
if all(x in b for x in a) and len(a)==len(b):
b=a[:]
If you want to make list2 identical to list1, you don't need to mess with order or re-arrange anything, just replace list2 with a copy of list1:
list2 = list(list1)
list() takes any iterable and produces a new list from it, so we can use this to copy list1, thus creating two lists that are exactly the same.
It might also be possible to just do list2 = list1, but do note that this will cause any changes to either to affect the other (as they point to the same object), so this is probably not what you want.
If list2 is referenced elsewhere, and thus needs to remain the same object, it's possible to replace every value in the list using list2[:] = list1.
In general, you probably want the first solution.
Sort b based on items' index in a, with all items not in a at the end.
>>> a=[1,4,5,2]
>>> b=[4,3,1,5]
>>> sorted(b, key=lambda x:a.index(x) if x in a else len(a))
[1, 4, 5, 3]
I was under impression that every object in a Scala List must have the same type and if we need to have a collection of something of different types, tuples should be used.
From Scala's documentation, List is
A class for immutable linked lists representing ordered collections of
elements of type.
scala> val l1 = List(1,2,3)
l1: List[Int] = List(1, 2, 3)
scala> val l1 = List(1,2,3, "oh really?!")
l1: List[Any] = List(1, 2, 3, oh really?!)
This does not seem to be the case. After all Any on its own is a valid Scala type and everything can be reduced to it.
Please clarify
You didn't specify the type of the list explicitly and you put in two types of objects, it would seem convenient that it makes this a list of type 'Any' and it doesn't break the rules.
If you had said val l1: List[Int] = List(1,2,3, "oh really?!") it would have been a different case (as in: it would tell you there's a type mismatch)
It doesn't always just resolve to Any either.
Consider you have a class called Vehicle and two classes inheriting from it called Bike and Car.
val car = new Car
val bike = new Bike
val vehicleList = List(car, bike)
vehicleList will now be of type Vehicle. If you had only put a Car or a Bike in there then it would have been of that specific type.
Optional background information: A List in Scala is covariant, meaning that if Int and String are subtypes of Any, then List[Int] and List[String] are also subtypes of List[Any]. This means you can have a list that contains Integers and Strings and is the reason that your statement is valid and automatically results in a List[Any]. This is not always a given fact by the way and can actually lead to trouble if the list is mutable. Luckily the default List in Scala isn't. If you want to know more, a longer explanation can be found at Covariance, Invariance and Contravariance explained in plain English?