I am new to coding in scala and I am curious about something and it has been hard to find an answer for online. I have this array that takes multiple arguments of different types (:Any)
val arguments= Array("Monday",10,20,Array("test","test2"), if(4 == 4){ "true"})
I iterated and printed the content inside of it. Everything prints properly except the Array at index 3. I get the object memory address I believe, which is understandable-- same thing with Java would happen. But I am curious, how would you access it?
I tried saving the value of arguments(3) in an array (val arr:Array[String] = arguments(3)) but it didn't work because there is a type mismatch (any != Array[String])
Any tips? It might be a gap in my understanding of functional programming.
What you are iterating through is an Array[Any], so you are able to perform functions that are available to an Any type. You can access the items in your array using pattern matching, which uses the unapply methods under the hood to see if it can turn your Any into something more specific:
val arguments= Array("Monday",10,20,Array("test","test2"), if(4 == 4){ "true"})
arguments foreach { arg =>
arg match {
case a:Array[String] => println(s"This is the array: ${a.mkString(",")}, and I can do array functions ${a.contains("test")}")
case _ => println(s"Otherwise I have this: $arg")
}
}
// stdout:
// Otherwise I have this: Monday
// Otherwise I have this: 10
// Otherwise I have this: 20
// This is the array: test,test2, and I can do array functions true
// Otherwise I have this: true
Related
I know that with tuples sizes of arrays can be defined. Not applicable to float32array which is a class itself though.
Can that somehow be done with float32arrays as well?
I tried const foo: FloatArray32[4] but that casts the type directly to the number.
I also tried to check if types might be compatible:
let foo: [number, number, number, number];
foo = new Float32Array([1, 2, 3, 4]);
But they are not.
Changing all the types in my code to '[number, number, number, number];' (in my case I need a 4 float array for a point coordinate) is a possibility, although I would need to make changes in quite a lot of places in the code.
However, I was wondering if there might be a 'childtype' extending Float32Array type, where the number of the elements of the array can be fixed in the type.
Javascript typed arrays, are in fact, fixed length - see the docs for your example. The constructors in particular:
new Float32Array(); // new in ES2017
new Float32Array(length);
new Float32Array(typedArray);
new Float32Array(object);
new Float32Array(buffer [, byteOffset [, length]]);
all have the length deducible on creation (that new first one creates an empty array with 0 elements. I guess it simplified some edge cases).
I'm not sure how you are determining the type, but as soon as you get an item from your array it will be converted to a number, the only number type available in JS - so looking at your log is misleading here. Take a look at the following static property:
Float32Array.prototype.byteLength
Returns the length (in bytes) of the Float32Array. Fixed at construction time and thus read only.
This is the only thing that counts. If you still don't believe the docs, try logging a cell after you overflow it (easier with int8 - put 200 or something). This is relevant to your example - nothing is being converted to a number. The array object is a view in fixed length numbers - again, run your test with an Int8Array and try to assign 200 to the cell, and read the cell.
This is a view into raw data. If you extract it and make mathematical operations, you are now in JS realm and working with Numbers - but once you assign stuff back, you better make sure the data fits. You cannot get JS/TS to show you something like float32 in your console, but each cell of the array itself does have an exact byte length.
unfortunately, making the length a part of the type is non-trivial within the type system as far as I can tell since the length is a property determined in construction (even if static and read only) and not a part of the type. If you do want something like this a thin wrapper could do the trick:
class vec4 extends Float32Array {
constructor(initial_values? : [number, number, number, number]) {
initial_values? super(initial_values) : super(4);
}
}
would do the trick. If you are willing to give up square brackets you can add index out-of-bound checking in the different methods (you can set in a fixed width array any cell, but it will do nothing, and retrieving it will yield undefined if out of bounds, which may be error prone):
get(index : number) {
if(index > 4 || index < 0) ...
return this.private_data[index];
}
set(index : number, value : number) {
if(index > 4 || index < 0) ...
this.private_data[index] = value;
}
Of course, without LSP in JS/TS the array and your class are still interchangeable, so enforcement is really only done on construction, and only if you do not try to break your own code (let foo : vec4; foo = new Float32Array([1, 2]); etc...).
I have read all the posts I can find here about arrays of functions - great you can do it. I figured. But none of the posts show practically how to use them (at least not what I'm trying to do). Here's what I want - they can all take the same args, but that's not a requirement.
This article is close, and will allow me to loop through to execute each function (which meets the first goal).
https://stackoverflow.com/a/24447484/11114752
But... what if I want to execute a single function by reference?
In other words, how to call just the referenced Arity2 function - for example:
// None of these work (with or without the parameter labels)
funcs.Arity2(n: 2, S: "Fred) // value of type [MyFuncs] has no member .Arity2
funcs[Arity2](n: 2, S: "Fred") // no exact matches to call in subscript
funcs[.Arity2](n: 2, S: "Fred") // Cannot call value of non-function type...
let fn = funcs.first(where: { a whole ton of permutations here to try to match Arity2 }) -- a whole lotta frustrating nope...
Help, please! Nothing I've tried works. The pre-compiler just goes in circles making suggestions that don't pan out and it will not compile.
EDIT:
The reason for the array in the first place is that I'm going to have a quite a few functions, and I don't know what they all are in advance. Essentially, I want a plugin type of architecture. Where I can add to the list of functions (ideally within an extension of the class, but that's another problem..) and not change the processing loop that executes each function in order.
I assume you need something like
_ = funcs.first {
if case let MyFuncs.Arity2(f) = $0 {
f(2, "Fred")
return true
}
return false
}
It can be achieved in a much simpler way if you know the position of the function in the array.
Assuming you have:
func someFunc(n: Int, s: String) {
print("call \(n) \(s)")
}
var funcs = [MyFuncs.Arity2(someFunc)]
you can do:
if case .Arity2(let f) = funcs.first {
f(2, "Fred")
}
By replacing funcs.first with funcs[i] you can access the i-th index (first make sure it does exist).
I'm new to scala/java and I have troubles getting the difference between those two.
By reading the scala doc I understood that ArrayBuffer are made to be interactive (append, insert, prepend, etc).
1) What are the fundamental implementation differences?
2) Is there performance variation between those two?
Both Array and ArrayBuffer are mutable, which means that you can modify elements at particular indexes: a(i) = e
ArrayBuffer is resizable, Array isn't. If you append an element to an ArrayBuffer, it gets larger. If you try to append an element to an Array, you get a new array. Therefore to use Arrays efficiently, you must know its size beforehand.
Arrays are implemented on JVM level and are the only non-erased generic type. This means that they are the most efficient way to store sequences of objects – no extra memory overhead, and some operations are implemented as single JVM opcodes.
ArrayBuffer is implemented by having an Array internally, and allocating a new one if needed. Appending is usually fast, unless it hits a limit and resizes the array – but it does it in such a way, that the overall effect is negligible, so don't worry. Prepending is implemented as moving all elements to the right and setting the new one as the 0th element and it's therefore slow. Appending n elements in a loop is efficient (O(n)), prepending them is not (O(n²)).
Arrays are specialized for built-in value types (except Unit), so Array[Int] is going to be much more optimal than ArrayBuffer[Int] – the values won't have to be boxed, therefore using less memory and less indirection. Note that the specialization, as always, works only if the type is monomorphic – Array[T] will be always boxed.
The one other difference is, Array's element created as on when its declared but Array Buffer's elements not created unless you assign values for the first time.
For example. You can write Array1(0)="Stackoverflow" but not ArrayBuffer1(0)="Stackoverflow" for the first time value assignments.
(Array1 = Array variable & ArrayBuffer1 = ArrayBuffer variable)
Because as we know, Array buffers are re-sizable, so elements created when you insert values at the first time and then you can modify/reassign them at the particular element.
Array:
Declaring and assigning values to Int Array.
val favNums= new Array[Int](20)
for(i<-0 to 19){
favNums(i)=i*2
}
favNums.foreach(println)
ArrayBuffer:
Declaring and assigning values to Int ArrayBuffer.
val favNumsArrayBuffer= new ArrayBuffer[Int]
for(j<-0 to 19){
favNumsArrayBuffer.insert(j, (j*2))
//favNumsArrayBuffer++=Array(j*3)
}
favNumsArrayBuffer.foreach(println)
If you include favNumsArrayBuffer(j)=j*2 at the first line in the for loop, It doesn't work. But it works fine if you declare it in 2nd or 3rd line of the loop. Because values assigned already at the first line now you can modify by element index.
This simple one-hour video tutorial explains a lot.
https://youtu.be/DzFt0YkZo8M?t=2005
Use an Array if the length of Array is fixed, and an ArrayBuffer if the length can vary.
Another difference is in term of reference and value equality
Array(1,2) == Array(1,2) // res0: Boolean = false
ArrayBuffer(1, 2) == ArrayBuffer(1,2) // res1: Boolean = true
The reason for the difference is == routes to .equals where Array.equals is implemented using Java's == which compares references
public boolean equals(Object obj) {
return (this == obj);
}
whilst ArrayBuffer.equals compares elements contained by ArrayBuffer using sameElements method
override def equals(o: scala.Any): Boolean = this.eq(o.asInstanceOf[AnyRef]) || (
o match {
case it: Seq[A] => (it eq this) || (it canEqual this) && sameElements(it)
case _ => false
}
)
Similarly, contains behaves differently
Array(Array(1,2)).contains(Array(1,2)) // res0: Boolean = false
ArrayBuffer(ArrayBuffer(1,2)).contains(ArrayBuffer(1,2)) // res1: Boolean = true
I wrote an array, where, when a hittest occurs, a number should be pushed into the array. However, when I use myArray.push, it enters the number, and when i call myArray.push again, instead of entering the number again and having 2 numbers in my array, it just enters the number in the same spot. So, if i use trace(myArray.length), no matter how many times it has pushed, it keeps saying I have 1 number stored.
This is my code:
if (hitTestObject(target.hit)) {
//pushes a number into an array
myArray.push();
//checks array length
if (myArray.length == 3) {
//do stuff
}
}
I've tried numbers, strings, and Math.random() in the parameters for myArray.push(), but I always get the same result of only having 1 item in my array.
For reference, this is how I wrote my variable for it:
public var myArray:Array = new Array();
You have to push something into the array. Try:
myArray.push(myArray.length);
However, it looks like you'd be better off just incrementing a number rather than creating an array. An array is a container of objects to be later referenced. So, unless you need to track that the third object in the array is in fact '2'...the array is useless. Try creating a number and increment the variable each time. Like this:
// Declared outside of the function
var integer:int = 0;
//
if (hitTestObject(target.hit)) {
integer = integer + 1;
// likewise you could use ++integer or integer++;
if (integer == 3) {
//do stuff
}
}
Based on your code, you are not actually pushing anything into the array.
The correct syntax is :
myArray.push(something);
Here is a simple code :
var a:Array = new Array( ins0, ins1, ins2, ins3,...., ins10000) ;
findIns( ins1500) ;
function findIns( ins:SomeInstance ) {
for ( var i = 0 ; i< a.length ; i++) {
if ( a[i] == ins ) {
trace ( "FOUND IT");
break;
}
}
}
In the above code there is NO "int" or "string". They are instances of some complex class. So is it sensible to use Vectors in place of arrays in this case.
In my opinion it should be sensible, because instances are "numerical-memory-locations" afterall ?
If the content of the array are all instances of the same class, then yes Vector will definitely performs better than Array.
See the documentation for more information:
Performance: array element access and iteration are much faster when using a Vector instance than they are when using an Array.
Type safety: in strict mode the compiler can identify data type errors. Examples of data type errors include assigning a value of the incorrect data type to a Vector or expecting the wrong data type when reading a value from a Vector. Note, however, that when using the push() method or unshift() method to add values to a Vector, the arguments' data types are not checked at compile time. Instead, they are checked at run time.
Reliability: runtime range checking (or fixed-length checking) increases reliability significantly over Arrays.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Vector.html
Yes, you are right. What gets stored inside the vector is a reference to your object, not your object itself. You can check that doing the following:
var ref:yourType = a[0];
a[0] = someOtherObjectInstance;
trace(ref.toString());
You will find that ref still points to your original object.