Swift: EXC_BAD_INSTRUCTION called when calling function - arrays

So I'm trying to get a standard deviation function to work, however I'm running into an error. Here's my code:
func standardDeviation(dataSet: [Double]) -> Double {
let mean = dataSet.reduce(0, +) / Double(dataSet.count)
var distances = [Double]()
for number in dataSet {
let distanceFromMean = (dataSet[Int(number)] - mean)
distances.append(distanceFromMean * distanceFromMean)
}
return distances.reduce(0, +) / Double(dataSet.count)
}
It outputs the following error:
Fatal Error: Index out of range
So, I had a feeling that it was something to do when I call the dataSet array, so when I looked into that, I found this as an error
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

number (a Double!) cannot be an index to subscribe dataSet, so I'm quite sure you mean
let distanceFromMean = number - mean
as in the Fast Enumeration pattern the index variable number is actually equal to array[index]

Related

QS5026 - The variable cannot be reassigned here

I'm following tutorial from the official Microsoft learning page (https://learn.microsoft.com/en-us/azure/quantum/tutorial-qdk-explore-entanglement?pivots=ide-azure-portal) about quantum entanglement.
Basically, I copied an example posted there and I am getting error:
QS5026 The variable "numOnesQ1" cannot be reassigned here. In conditional blocks that depend on a measurement result, the target QuantinuumProcessor only supports reassigning variables that were declared within the block.
I understand what it says but it's just a copy from the official Microsoft tutorial. Am I missing something simple like imports, wrong settings? If not, how can I in other way set variables declared outside conditional blocks that depend on a measurement result?
Here is my code:
namespace Quantum.QuantumDream {
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Intrinsic;
operation GetRandomResult() : Result {
use q = Qubit();
H(q);
return M(q);
}
#EntryPoint()
operation TestBellState(count : Int, initial : Result) : (Int, Int, Int, Int) {
mutable numOnesQ1 = 0;
mutable numOnesQ2 = 0;
// allocate the qubits
use (q1, q2) = (Qubit(), Qubit());
for test in 1..count {
SetQubitState(initial, q1);
SetQubitState(Zero, q2);
// measure each qubit
let resultQ1 = M(q1);
let resultQ2 = M(q2);
// Count the number of 'Ones':
if resultQ1 == One {
set numOnesQ1 += 1;
}
if resultQ2 == One {
set numOnesQ2 += 1;
}
}
// reset the qubits
SetQubitState(Zero, q1);
SetQubitState(Zero, q2);
// Return number of |0> states, number of |1> states
Message("q1:Zero, One q2:Zero, One");
return (count - numOnesQ1, numOnesQ1, count - numOnesQ2, numOnesQ2 );
}
operation SetQubitState(desired : Result, target : Qubit) : Unit {
if desired != M(target) {
X(target);
}
}
}
This tutorial code is only supposed to run on a local simulator (using %simulate magic commands in a Jupyter Notebook). From the error message, it looks like you've tried to run it on one of Quantinuum targets, which have some limitations on the kinds of things you can do in the code. To run equivalent code on Quantinuum, you'd need to define an operation for just the body of the loop (preparing a state and measuring it) and run it as a job - the cloud targets will take care of the loop themselves, running your code multiple times and returning to you a histogram of the results. For an example, you can see the QRNG sample in the samples gallery in Azure Portal.

Looping through an array to get index of item - swift

I am trying to loop through an array of names to get the index of a certain string. I then want to set the index of my UIPicker to the said string.
I have the following code however this causes the app to crash due:
let index = self.nameArray.index(where: {$0 == assetArray[0].Owner })
scroll_owners.selectRow(index ?? 0, inComponent: 0, animated: true)
When debugging the index is getting a value of index 6176573120 which of course isn't in the range of my UIPicker so causes the crash.
Any ideas on why this may be happening?
Using the suggested answer throws the following error:
unrecognized selector sent to instance 0x101134af0'
There is definitely a match in assetArray[0] with the name that is being passed through.
Doing a bit more investigation trying to run the following line of code alone gives the same error:
scroll_owners.selectRow(0, inComponent: 0, animated: true)
Does this mean I'm missing a delegate method?
Asset Array and Name Array:
var assetArray : [Asset] = []
var nameArray = [String]()
EDIT:
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
self.scroll_owners.delegate = self
self.scroll_owners.dataSource = self
I've tried to get this working another way - I know this is an ugly way of doing it I'm just trying to see why the accepted swift way isn't working:
var i : Int = 0
while (nameArray[i] != name)
{
print(nameArray[i])
i=i+1
}
scroll_owners.selectRow(i, inComponent: 0, animated: true)
This section of code crashes and the while loops is never entered due to the index being out of bounds - does this mean the issue could be with nameArray?
i think the problem is that .index doesn't return an IndexPath.
But selectRow needs an indexPath as parameter.
.index
.selectRow
I have managed to solve this error myself in a slightly different way.
In my function which populates the nameArray and the UIPicker I have placed the following code:
var i : Int = 0
while (self.nameArray[i] != name)
{
print(self.nameArray[i])
i=i+1
}
self.scroll_owners.selectRow(i, inComponent: 0, animated: true)
The reason the code was crashing was due to the fact that the nameArray was not finishing being populated before I was trying to do the comparisons. I know this may not be the accepted swift way of doing this but it works.
The issues were caused due to the function being run on a seperate thread I believe.

Unable to return a filtered array

Overview
I am new to the Swift language, but not others, and am having trouble executing a simple Array.filter statement that I would like to return as the result for a function in a class I am writing, but it seems adding the return keywords causes non-intuitive compile errors.
Question: Does anyone know what to make of these error messages, and how to fix them?
Samples
Declarations
var arrDictIVar = [["dictVar1": "value"]]
...
func someFunc(var1: String) {...
Various Trials
Set 1
return arrDictIVar.filter({
$0["dictVar1"] == var1
})
return arrDictIVar.filter(){
$0["dictVar1"] == var1
}
return arrDictIVar.filter{
$0["dictVar1"] == var1
}
Error: Cannot invoke 'filter' with an argument list of type '(#noescape ([String : String]) throws -> Bool)'
Error Subtext: Expected an argument list of type '(#noescape (Self.Generator.Element) throws -> Bool)'
Source: Sample MCVE Execute here
Set 2
return arrDictIVar.filter({
$0["dictVar1"] == var1
})[0]
return arrDictIVar.filter() {
$0["dictVar1"] == var1
}[0]
return arrDictIVar.filter{
$0["dictVar1"] == var1
}[0]
Error: Cannot subscript a value of type '[[String : String]]'
Source: Sample MCVE Execute here
Set 3
arrDictIVar.filter({
$0["dictVar1"] == var1
})
arrDictIVar.filter(){
$0["dictVar1"] == var1
}
arrDictIVar.filter{
$0["dictVar1"] == var1
}
Warning: Result of call to 'filter' is unused
Note: Just to show that the block is properly formed without the return keyword.
Source: Sample MCVE (Execute here)
Other Information
I have also tried modifying the IVar declaration to var arrDictIVar: Array<Dictionary<String,String>> = [..., and the function declaration to func someFunc(var1: String) -> Dictionary<String,String>{... at various times, with similar failures.
Edit: I had posted an answer at the same time of this question as I found a combination that worked towards nearing the end of this posting. It does include changing the return data type in the method signature, along with giving other information alluding to the inaccurate, or at least confusing nature, of the compiler, and the error messages it presents.
After this I was left with a follow-up question:
If anyone would be able to explain why this was happening, and give a clear judgement as the compiler error message was not as helpful as it could be, my reading/interpretation of the error message was not as clear as it could have been, potentially saving time by changing my mindset somehow, or either, please comment on that note.
Victor Sigler's answer does seem to cover this in some good detail.
Let's explain in detail every set you have put in your question:
Set 1:
Your three examples are right in code and are the same to the compiler, you're using a trailing closure and the parentheses can be omitted.
Sometimes the compiler(because it's so young yet!!!) not show the exactly error happening in your code, but definitely in this step you're using the filter function to return an [[String: String]] or an array of dictionaries and you're missing the type of the return of the function, it's assumed by the compiler as Void.
About #noescape:
Adding #noescape guarantees that the closure will not be stored somewhere, used at a later time, or used asynchronously. Remember that closures capture values.
You can read more about the #noescape clause in the following two very good tutorials:
#noescape Attribute
Hipster Swift: Demystifying the Mysterious — KrakenDev
So to resume it, if you change your function to the following it should work:
func someFunc(var1: String) -> [[String: String]] {
return arrDictIVar.filter({
$0["dictVar1"] == var1
})
}
Set 2:
If you fix the error in the Set 1 then when you code:
return arrDictIVar.filter{
$0["dictVar1"] == var1
}[0]
You're trying to return a [String: String] or a dictionary and it's wrong regarding the return type of the function it's [[String: String]].
But be careful because if you change the return type to [String: String] and try to index the array returned for the filter function and there is nothing founded by the filter function you would get an runtime error.
Set 3
I think it is the more easy to understand because as the warning said, the filter function returns a new list of elements and if you don't save it or returned in your function it's unused, something like this:
func someFunc(var1: String){
arrDictIVar.filter({
$0["dictVar1"] == var1
})
}
I hope this help you.

Error with APAddressBOOK: "fatal error: Array index out of range"

I am receiving this strange error every time I process an address book ( using APAddressBOOK via cocapods) in Swift and after some debugging I found out that and empty object (record with no phone number) within the array causes this issue but am not sure how to get rid of it.
Here is my code:
func getPersonsNo(contactno: AnyObject) -> String {
println(contactno) // **when the object is empty I get this "[]"**
if let numberRaw = contactno.phones?[0] as? String { // at this statement the program crashes with a fatal error
println(numberRaw)
return numberRaw)
}
return " "
}
Any clues what is happening here?
The subscript of an Array doesn't return an optional to indicate if an index is out of range of the array; instead your program will crash with the message “fatal error: Array index out of range”. Applying this your code: when contactno is empty your program will crash because there's no element at index 0 of the array.
To easiest way to solve your problem is probably to use the first property on Array. first will return the first element in the array, or nil if the array is empty. Taking a look at how first is declared:
extension Array {
var first: T? { get }
}
As of Swift 2, first has been made an extension of the CollectionType protocol:
extension CollectionType {
var first: Self.Generator.Element? { get }
}
You'd use this like so:
if let numberRaw = contactno.phones?.first as? String {
// ...
}

R, Integrate at each point of array

I'm stuck with computing the integral at each point of an array. The idea is first to create a function ("Integrand"). Then, create a second function ("MyConvolve") that computes the necessary integral.
Here's what I did up to now:
Integrand = function(s,x)
{ 1/4*(abs(x-s)<=1)*(abs(s)<=1) }
MyConvolve = function(func,data)
{ return( integrate(func, lower=-Inf, upper=Inf, data) ) }
Now, running the code with some array, I get an error message:
SomeMatrix = replicate(10, rnorm(10))
MyConvolve(Integrand, SomeMatrix)
Which ends up with the following error message:
Error in integrate(func, lower = -Inf, upper = Inf, data) :
evaluation of function gave a result of wrong length
I already tried vectorizing the function, but still ended up with error messages.
Thank you very much for your help!
I am not sure I understand what you are trying to compute,
but if you want to evaluate MyConvolve(Integrand,s),
where s takes all the values in SomeMatrix,
then apply is sufficient.
sapply( SomeMatrix, function(s) MyConvolve( Integrand, s )$value )
However, the dimensions of the matrix are lost.
You can recover them as follows:
result <- SomeMatrix
result[] <- sapply( SomeMatrix, function(s) MyConvolve( Integrand, s )$value )

Resources