Assigning a value to an element of a tuple in Julia - tuples

I am facing a problem with tuples in Julia. Here is what I am trying to do
julia> temp = [1 2 3]
julia> A = tuple(temp, temp)
julia> B = tuple(A,A,A)
B looks like this :
julia> B
((
[1 2 3],
[1 2 3]),(
[1 2 3],
[1 2 3]),(
[1 2 3],
[1 2 3]))
I understand I can access the 'very' first element in B by
B[1][1][1] which returns 1 (as expected)
But, if I try to assign a particular value to B[1][1][1], say if I do,
julia> B[1][1][1] = 20, this is what I get,
julia> B
((
[20 2 3],
[20 2 3]),(
[20 2 3],
[20 2 3]),(
[20 2 3],
[20 2 3]))
The first elements of all the sub-tuples have been changed. Is there a way to change the value of B[1][1][1] without affecting the other sub-tuples ??
Thanks in advance.
PS : I'm using Julia 0.5.0 on Ubuntu 16.04 (64-bit)

This is not quite a problem with tuples. Exactly the same thing will happen if you use arrays.
A = (temp, temp) will reference the same address in memory twice. So you need to do A = (copy(temp), copy(temp))
But ...
copy(x)
Create a shallow copy of x: the outer structure is copied, but
not all internal values. For example, copying an array produces a new
array with identically-same elements as the original.
So for B = (A, A, A) we need to use deepcopy in order to get the values (rather than the references) of each variable. i.e. B = (deepcopy(A), deep copy(A), deepcopy(A))
Check out the docs for copy and deepcopy here:
http://docs.julialang.org/en/release-0.4/stdlib/base/#Base.copy

A = tuple(temp, temp)
You make this a tuple of all the same arrays (note you can just write A = (temp,temp)). If you want to use a copy of the array, use A = (copy(temp),copy(temp)). The value of an array is its reference, and thus when you do A = (temp,temp), you just have two references to the same slab of memory, which is why when you change one, the other changes.

Equal sign (a=b)
simple types are deep copied
containers of simple types (or other containers) are shadow copied (their internal is only referenced, not copied)
copy(x)
simple types are deep copied
containers of simple types are deep copied
containers of containers: the content is shadow copied (the content of the content is only referenced, not copied)
deepcopy(x)
everything is deep copied recursively

Related

Difference between List.subList and slice in Kotlin

I recently realised there are two very similar functions in Kotlin for getting a portion of a List, but I'm unsure of the difference:
The documentation for List.subList says:
Returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive). The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
Structural changes in the base list make the behavior of the view undefined.
whereas the documentation for slice says:
Returns a list containing elements at indices in the specified indices range.
Or
Returns a list containing elements at specified indices.
It seems that the key differences are that the first one returns a "view of the portion" of the list, and whether non-structural changes are reflected? However I'm not quite sure what this means.
I looked at the source code for the slice function:
public fun <T> List<T>.slice(indices: IntRange): List<T> {
if (indices.isEmpty()) return listOf()
return this.subList(indices.start, indices.endInclusive + 1).toList()
}
But it returns a list from the subList function.
Could someone explain the differences between these two functions and when you might want to use one over the other?
The key in List<T>.slice function is the .toList() at the end.
The call to toList() will create a new List with all the elements, like a copy.
For summary:
.slice() will create a new List with the subset of elements
.subList() is only a view of the original List that will change with it.
You can see differences here: https://pl.kotl.in/-JU8BDNZN
fun main() {
val myList = mutableListOf(1, 2, 3, 4)
val subList = myList.subList(1, 3)
val sliceList = myList.slice(1..2)
println(subList) // [2, 3]
println(sliceList) // [2, 3]
myList[1] = 5
println(subList) // [5, 3]
println(sliceList) // [2, 3]
}

Weird thing of Array.create in OCaml

I'm a newbie at OCaml. And when I do some coding using array in Ocaml I come to a problem I can't understand.
Here is the code:
let a = Array.create 5 (Array.create 5 0);
a.(0).(1) <- 1
I just want to assign 1 to a[0][1] but then things happened: all the element in the first colummn has been assigned. That is, a[0][1], a[1][1], a[2][1], a[3][1] and a[4][1] are all equal to 1 after the code above executed.
If I create the array using:
Array.make_matrix 5 5 0
everything is fine.
My environment:
Ubuntu 13.10
Ocaml 4.01.0
open Core.Std
This is a common pitfall of Array.create. Use Array.init instead when your array element is boxed.
Array.create initializes the array elements with the same value: if the value is boxed, with the same pointer. In your case, all the elements a.(i) points to the same array created by Array.create 5 0.
Correct code should be
let a = Array.init 5 (fun _ -> Array.create 5 0)
This creates 5 individual arrays.
You should check this Q/A: Ocaml - Accessing components in an array of records
You only call Array.create twice, so only two arrays are created -- one whose elements all point to the other.
Array.create creates an array and sets each element to a copy of the value given. So it's as if you did this:
let x = Array.create 5 0;
let a = Array.create 5 <some dummy value>;
a.(0) <- x;
a.(1) <- x;
a.(2) <- x;
a.(3) <- x;
a.(4) <- x;
See the problem? All five elements are set to x, a pointer to the same array.
Note that all types in OCaml are basically reference types. (Technically, int and some smaller types like char and bool, and algebraic data types with all no-arg constructors, are implemented as value types. But value types are semantically equivalent to immutable reference types except for physical equality. So you can think of all types as reference types for simplicity.)
Just for more information:
Here is the doc of Array: http://caml.inria.fr/pub/docs/manual-ocaml/libref/Array.html
val make : int -> 'a -> 'a array
Array.make n x returns a fresh array of length n, initialized with x. All the elements of this new array are initially physically equal to x (in the sense of the == predicate). Consequently, if x is mutable, it is shared among all elements of the array, and modifying x through one of the array entries will modify all other entries at the same time.
Raise Invalid_argument if n < 0 or n > Sys.max_array_length. If the value of x is a floating-point number, then the maximum size is only Sys.max_array_length / 2.
val create : int -> 'a -> 'a array
Deprecated. **Array.create is an alias for Array.make**.

Prolog evaluating how two lists compare to eachother

Note: Near complete beginner to logic programming
I need to compare two lists of integers and figure out if one is greater, greater-equal, or they are both equal.
For example:
compare_list([1, 2, 3], [1, 2, 4], C).
C = greater,
C = greater-equal.
compare_list([1, 2, 3], [1, 2, 4], C).
C = equal.
So far the closest I have been able to get has been...
compare_list([],[],_).
compare_list([X|XS],[Y|YS],C):-
X > Y,
compare_list(XS,YS,C),
C = 'greater'.
compare_list([X|XS],[Y|YS],C):-
X >= Y,
compare_list(XS,YS,C),
C = 'greater-equal'.
compare_list([X|XS],[Y|YS],C):-
X == Y,
compare_list(XS,YS,C),
C = 'equal'.
Now that obviously doesn't work as needed because it is always comparing the first element of each list and seeing if the C value holds for all of the values. However I cannot think of a way to make it work as intended.
Edit:
The earlier a value is in a list, the more important it is. So [2,2] > [1,3] > [1,2]
Tips would be appreciated. Thanks.
Edit:
Solved by waiting until the end to assign C to anything.
In your solution you use (>)/2, (>=)/2 and (==)/2. The first two will evaluate their arguments as arithmetic expressions prior to a comparison. And (==)/2 will compare due to term order. You will have to decide for one of them or another term order. But you cannot mix them.
The second remark is that you would also need something as 'less' as a result.
If two elements already compare as (<)/2, there is no need for further comparison.
Also, equality can only be stated in the fact, but not before.
Consider to use the built-in predicate `compare/3`:
?- compare(R, [1, 2, 3], [1, 2, 4]).
R = (<).
?- compare(R, [1, 2, 3], [1, 2, 3]).
R = (=).
Should you write your own comparison predicate, better use the very same argument order and the same terms as result. That is, <, =, and >. It does not make a lot of sense, to expect >= to be a result. After all, two identical lists would then have three different solutions =<, =, >=.
From your description, it is not clear to me what you expect, if both lists are of different length.
According to your definition of "greater" there is no need to continue the recursion after you find that X>Y. If you reach the end of the recursion (as chac said) you'll know that the two lists are equal.
To get "greater-equal" you should instead check that X is not less than Y. You may think of this as "if X is less than Y than fail". Take a look at negation as failure.
You can stop comparing at the first ineguagliance. If you reach the end of (both) lists, that means lists are equals.
The following code will check whether two list are equal or not
is_equal([],[]).
is_equal([H1|T1],[H2|T2]):- H1=:=H2,is_equal(T1,T2).

Prolog length of a list

How can I calculate the length of a list
?- size_sub([[b,a,g], [9,3,7,4], [6]], X).
X = [3, 4, 1].
?- size_sub([[c,g,e,w], [7]], X).
X = [4, 1].
?- size_sub([], X).
X = [].
Ok you need to start with the base case which is the last answer
so size_sub([],X). is true if X=[] so first you write that as a rule.
size_sub([],[]).
Then you need to do the inductive step a list that is one longer than the previous. I am going to assume that you have a size/2 function for determining the size of a single list (if not please comment).
So the inductive step is going to operate on the length of the first parameter so N->N+1. We would represent this by striping off the head of the list syntax will be [H|T] now the second parameter (your answer) is going to be the length of H with the result of calling size_sub on T. As we cannot specify rules in the parameters in the header we will use N to represent the length of H and T2 to represent the result of size_sub on T.
So the first part of the rule becomes size_sub([H|T],[N|T2]):-
now we follow it with the predicates that will assert the values for N and T2.
size(H,N),
size_sub(T,T2).
putting that all together you get
size_sub([],[]).
size_sub([H|T],[N|T2]):-
size(H,N),
size_sub(T,T2).
size/2 is a far simpler case and following the same process of base + inductive you should be able to create the rules for it. Please comment if you need further help.
** EDIT - Request for size/2 definition **
To define size/2
Start with the base case, the empty list has a size of 0.
size([],0).
Now the inductive step. The size of list of length(N+1) is the size of a list of length(N). So lets define our list as [_|T] I've defined the list using _ to represent the head because we never use it so we can just use the anonymous variable. Lets use N to represent the length of T, and M to be N+1.
so
size([_|T],M):-
now lets define N
size(T,N),
and finally assert that M is equal to N + 1
M is N+1.
so putting everything together
size([],0).
size([_|T],N):-
size(T,M),
N is M+1.
size_sub([],[]).
size_sub([H|T],[N|T2]):-
size(H,N),
size_sub(T,T2).
To map length/2 over a list of lists, we can use the meta-predicate maplist/3 like this:
size_sub(Xss,Ls):-
maplist(length,Xss,Ls).

In Scala, is there a way to take convert two lists into a Map?

I have a two lists, a List[A] and a List[B]. What I want is a Map[A,B] but I want the semantics of zip. So started out like so:
var tuplesOfAB = listOfA zip listOfB
Now I'm not sure how to construct a Map from my tuplesOfAB.
As a follow-up question, I also want to invert my map so that from a Map[A,B] I can create a Map[B,A]. Can anyone hit me with a clue-stick?
In 2.8 this is really simple using the CanBuildFrom functionality (as described by Daniel) and using breakOut with a type instruction to the compiler as to what the result type should be:
import scala.collection.breakOut
val m = (listA zip listB)(breakOut): Map[A,B]
The following would also work:
val n: Map[A,B] = (listA zip listB)(breakOut)
And (as EastSun, below, has pointed out) this has been added to the library as toMap
val o = (listA zip listB).toMap
As for reversing the map, you can do:
val r = m.map(_.swap)(breakOut): Map[B, A]
Now that you've got a list of tuples it is easy to make it into a map by writing Map(tuplesOfAB: _*). The : _* notation means to call the varargs overload with the arguments taken from the sequence. This seems like a funny bit of syntax, but it helps to think that varargs are declared like Map[A,B](pairs: (A,B)*) and the : _* is a type annotation to convert to varargs because of the common * part.
To reverse a map m use Map(m.map(_.swap): _*). In scala a map is also a collection of pairs. This transforms those pairs by swapping the elements and passing them to the Map constructor.
There's yet another way to do it, beyond those already shown. Here:
Map() ++ tuplesOfAB
scala> List( "a", "f", "d") zip List(7, 5, 4, 8) toMap
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map(a -> 7, f -> 5, d -> 4)