Does anyone know how I could implement I predicate doing what this one does but without "findall"?
Thank you a lot.
domains
oferta = rebaixat ; normal
element = string
list = element*
database
producte (string, integer, oferta)
predicates
nondeterm reduced2(list)
clauses
producte("Enciam",2,rebaixat).
producte("Peix",5,normal).
producte("Llet",1,rebaixat).
producte("Formatge",5,normal).
reduced2(Vals):-
findall(Val, producte(Val,_,rebaixat),Vals).
Goal
write("Amb findall"),nl,
reduced2(List).
I don't know much about Visual Prolog, but I will try to give a general answer. It depends on whether you want to find a findall/3 replacement for a specific case or in general, though.
In the specific case, you can use an accumulator. In your case, this would be a list into which the values are added as you find them. Something like:
acc(In, List) :-
... % do something to generate possible next value
... % test if value is already in list In
!,
Out = [Val|In], % adds to the head, but is faster than using append
acc(Out, List).
acc(List, List).
I.e., when you can't find another possible value, you return the list of values that you found. Note that this may be slow if you have to accumulate a lot of values and generating the next possible value is done via backtracking. Also, this will not let you generate duplicates, so it's not an exact replacement for findall/3.
If you want a general replacement for findall/3, where you can specify a goal and a variable or term that will contain the instance to be accumulated, then you won't get around using some sort of non-logical global variable. After finding the next value, you add it to what's been stored in the global variable, and cause backtracking. If generating the next value fails, you retrieve the content of the global variable and return it.
Related
I want to have a function within which several if conditions looking for specific integer values.
The function in some situations might be called several times in sequence in order to return the resulting values of several different if conditions.
The idea I had for this, in order to reduce the code's bulkiness, was to have the portion of the script executing the function as required run through an integer array whose each stored value is sent to the function.
But in order for this to reduce the amount of bulky code I need a way to add several values at once rather than having the values each added separately.
Is that possible in Pinescript? Or perhaps you have a different solution for executing such function?
To answer my own question, it seems a simple way to update an array to a set of new values is to use the built in function array.from.
var array<int> arr = array.new<int>(0, 0)
arr := array.from(1, 4, 10)
It doesn't even require clearing and appending the new values as it simply replaces the testArr array with the new input.
If one wants to append several additional values to an existing array rather than replacing all of the original values, it can be done like this:
arr := array.concat(arr, array.from(1, 4, 10))
If I understand your question correctly you would like a single mass update (addition) to array elements? No such function exists, each element must be individually updated, ideally in a loop if you have a consistent calculation.
From my understanding, an array is a simple table of values, such as local t = {"a","b","c"}, and a dictionary is a table of objects, such as local t = {a = 1, b = 2, c = 3} Of course, let me know if I'm wrong in either or both cases.
Anyways, my question lies in how we index the entries in either of these cases. For example, let's say I have the following code:
local t = {"TestEntry"}
print(t["TestEntry"])
Of course, this prints nil. However, when we use a dictionary the same way:
local t = {TestEntry = 1}
print(t["TestEntry"])
This, naturally, prints 1. My question is, why does it work this way for dictionaries, but not arrays?
Finally, I'd like to address the issue that led me to this question. Let's say, before I want to run a chunk of code, I need to see if a specific value is inside a table. It would be convenient if I could just check if it is in the table with table["GivenEntry"], but, as we have seen, this would only work if the entry in the table is actually an object. In my specific case, I am simply using an array, so it is not an object.
Thus, I had to resort to using a for loop to check the table:
local t = {"TestEntry1","TestEntry2"}
for i,v in pairs(t) do
if v == "TestEntry1" then
--do code
end
end
After doing this, it almost seemed as if it would be easier to create a silly dictionary, like:
local t = {TestEntry1 = "TestEntry1"}
because then, I could simply run t["TestEntry1"], and I wouldn't have to worry about having an empty table (because then the for loop would not run). Are there ramifications to creating a dictionary for such purposes? Is it less efficient in general?
Your input is appreciated,
Thank you.
In Lua both arrays an dictionaries are the same type (the table). local t = {"TestEntry"} is essentially short for local t = {[1] = "TestEntry"} (The brackets are needed by Lua for a number, you would access it with t[1]).
So the options for checking if "TestEntry1" is in the table are as you have written. A dictionary takes more memory and depending on how many values you have may take a while to create, but accessing a key should be constant time. Whereas to loop through the table will take longer and longer the more items you have so it is a tradeoff you have to decide on.
There are faster ways to search an array however (e.g. if it is sorted: https://en.wikipedia.org/wiki/Binary_search_algorithm)
I am taking a MATLAB programming class and we are currently working on a project which uses a database called Project2 of several structs of airline flight data (all 1 x N). One exercise requires us to create a function that identifies the number of flights segments (housed in the flights struct) that used the Boeing 737-800 aircraft. Below I have included the code for the function I created (NOTE: The format of the first line is such that was dictated in the instructions and must remain that way). Although this function seems to work and be free of bugs, it consistently returns a result of 0 and I cannot figure out why. Can anyone help? Suggestions for fixing the problem and/or cleaning up the code would be greatly appreciated!
function total = Problem2 (flights, aircraft, airlines, airports)
load Project2
id=findAircraftID (aircraft, Boeing 737-800)
seg=0;
for jj = 1:length(flights)
if (strcmp (flights(1,jj).aircraft_id, id))
seg=seg+1
end
end
fprintf ('A total of %d flight segments used the Boeing 737-800 aircraft.\n', seg)
end
function id=findAircraftID (aircraft, AircraftName)
id=0;
for ii=1:length(aircraft)
if (strcmp (aircraft(1,ii).name, AircraftName))
id=ii;
return;
end
end
end
Why are you using strcmp to compare integers? Is aircraft_id a string? Perhaps you can cast id from an int to a string if so. Or better yet you can just use isequal(a,b):
if isequal(flights(1,jj).aircraft_id, id)
seg=seg+1;
end
Also see other methods at Octave/MATLAB: How to compare structs for equality?
Also (or alternatively if that's not the issue) you're iterating through your second function and setting id several times, but only the last value goes into the first function. Take a closer look at your for loops to see whether you need to wrap them, store id as an array rather than a single integer, etc.
Never mind I see that your code could work if aircraft names are unique. strcmp should work in that case - but perhaps step through and check that you aren't having issues because of capitalization, spaces, etc.
Usually when you want to find an element in an array that matches a condition, you use something like
bWhenAis3 = B(A == 3);
To find the value of B when A is 3. This can return a vector of multiple values, and is usually much faster than an explicit loop.
In your code, aircraftID is an integer because it's returned by findAircraftID which returns ii. You cannot compare this with a string! You need to compare like types.
I am writing a program in C that reads a file. Each line of the file is a string of characters to which a computation will be done. The result of the computation on a particular string may imply that strings latter on in the file do not need any computations done to them. Also if the reverse of the string comes in alphabetical order before the (current, non-reversed) string then it does not need to be checked.
My question is would it be better to put each string in a linked list and delete each node after finding particular strings don’t need to be checked or using an array and checking the last few characters of a string and if it is alphabetically after the string in the previous element skip it? Either way the list or array only needs to be iterated through once.
Rules of thumb is that if you are dealing with small objects (< 32 bytes), std::vector is better than a linked list for most of general operations.
But for larger objects, (say, 1K bytes), generally you need to consider lists.
There is an article details the comparison you can check , the link is here
http://www.baptiste-wicht.com/2012/11/cpp-benchmark-vector-vs-list/3/
Without further details about what are your needs is a bit difficult to tell you which one would fit more with your requirements.
Arrays are easy to access, specially if you are going to do it in a non sequential way, but they are hard to maintain if you need to perform deletions on it or if you don't have a good approximation of the final number of elements.
Lists are good if you plan to access them sequentially, but terrible if you need to jump between its elements. Also deletion over them can be done in constant time if you are already in the node you want to delete.
I don't quite understand how you plan to access them since you say that either one would be iterated just once, but if that is the case then either structure would give you the similar performance since you are not really taking advantage of their key benefits.
It's really difficult to understand what you are trying to do, but it sounds like you should create an array of records, with each record holding one of your strings and a boolean flag to indicate whether it should be processed.
You set each record's flag to true as you load the array from the file.
You use one pointer to scan the array once, processing only the strings from records whose flags are still true.
For each record processed, you use a second pointer to scan from the first pointer + 1 to the end of the array, identify strings that won't need processing (in light of the current string), and set their flags to false.
-Al.
Here is a code snippet, that shows what I want and the error, that follows:
a = [1, 2];
m = containers.Map('KeyType','char', 'ValueType','any');
m('stackoverflow.com') = a;
pull_the_first_element_of_the_stored_array = m('stackoverflow.com')(1);
??? Error: ()-indexing must appear last in an index expression.
How do I access an element of the array, which is in turn a value of a map object?
I could have done this:
temp = m('stackoverflow.com');
pull_the_first_element_of_the_stored_array = temp(1);
But I do not want to create an intermediate array only to pull a single value out of it.
EDIT : This is a duplicate of How can I index a MATLAB array returned by a function without first assigning it to a local variable? The answer is there.
This is another case where you can get around syntax limitations with small helper functions. EG:
getFirst = #(x)x(1);
pull_the_first_element_of_the_stored_array = getFirst(m('stackoverflow.com'));
This still needs two lines, but you can often reuse the function definition. More generally, you could write:
getNth = #(x, n) x(n);
And then use:
getNth (m('stackoverflow.com'),1);
Although this question is a duplicate of this previous question, I feel compelled to point out one small difference between the problems they are addressing, and how my previous answer could be adapted slightly...
The previous question dealt with how to get around the syntax issue involved in having a function call immediately followed by an indexing operation on the same line. This question instead deals with two indexing operations immediately following one another on the same line. The two solutions from my other answer (using SUBSREF or a helper function) also apply, but there is actually an alternative way to use SUBSREF that combines the two indexing operations, like so:
value = subsref(m,struct('type','()','subs',{'stackoverflow.com',{1}}));
Note how the sequential index subscripts 'stackoverflow.com' and 1 are combined into a cell array to create a 1-by-2 structure array to pass to SUBSREF. It's still an ugly one-liner, and I would still advocate using the temporary variable solution for the sake of readability.