Why does the rebol interpreter return different results? - rebol

Consider:
>> print max 5 6 7 8
6
== 8
The documentation states that max only takes two arguments, so I understand the first line. But from the second line it looks like the interpreter is still able to find the max of an arbitrary number of args.
What's going on here? What is the difference between the two results returned? Is there a way to capture the second one?

I don't really know Rebol but what I do notice is that you're using print inside of th REPL. The first output is from print, which is outputting the result of max 5 6. The second output is from the REPL, which is outputting the value of your whole expression — which is maybe just the last item in the list? If you changed the order of your inputs, I bet you would see a different result.

max is an abbreviation for maximum. As #hobbs correctly guessed, it takes two arguments, and what you're seeing is just the evaluator's logic of turning the crank...and becoming equal to the last value in the expression. In this case you're not using that result, so the interpreter shows it to you with "==". But you could have assigned that whole expression to a variable (for instance).
What you were intending is something that gets the maximum value out of a series. In the DO dialect all functions have fixed arity, and the right way to design such a beast would be to make it take one argument...the series.
Such a thing does exist, though there isn't an abbreviation...
>> print maximum-of [5 6 7 8]
8

Related

Count will not work for unique elements in my dataframe, only when repeated

I want to count the number of occurences in a dataframe, and I need to do it using the following function:
for x in homicides_prec.reset_index().DATE.drop_duplicates():
count= homicides_prec.loc[x]['VICTIM_AGE'].count()
print(count)
However, this only works for when the specific Date is repeated. It does not work when dates only appear once, and I don't understand why. I get this error:
TypeError: count() takes at least 1 argument (0 given)
That said, it really doesn't make sense to me, because I get that error for this specific value (which only appears once on the dataframe):
for x in homicides_prec.reset_index().DATE[49:50].drop_duplicates():
count= homicides_prec.loc[x]['VICTIM_AGE'].count()
print(count)
However, I don't get the error if I run this:
homicides_prec.loc[homicides_prec.reset_index().DATE[49:50].drop_duplicates()]['VICTIM_AGE'].count()
Why does that happen??? I can't use the second option because I need to use the for loop.
More info, in case it helps: The problem seems to be that, when I run this (without counting), the output is just a number:
for x in homicides_prec.reset_index().DATE[49:50].drop_duplicates(): count= homicides_prec.loc[x]['VICTIM_AGE']
print(count)
Output: 33
So, when I add the .count it will not accept that input. How can I fix this?
There are a few issues with the code you shared, but the shortest answer is that when x appears only once you are not doing a slice, rather you are accessing some value.
if x == '2019-01-01' and that value appears twice then
homicides_prec.loc[x]
will be a pd.DataFrame with two rows, and
homicides_prec.loc[x]['VICTIM_AGE']
will be a pd.Series object with two rows, and it will happily take a .count() method.
However, if x == '2019-01-02' and that date is unique, then
homicides_prec.loc[x]
will be a pd.Series representing row where the index is x
From that we see that
homicides_prec.loc[x]['VICTIM_AGE']
is a single value, so .count() does not make sense.

Wiki API - Parsing sentences from JSON extracts in JavaScript?

Is there a way to have wiki display extracts in an array of sentences?
Or does anyone have any ideas other than using string.split(".") to parse? There are cases where the sentence may include a . and I don't want to split if it occurs mid-sentence.
For example, "The Eagles were No. 1 in the U.S. in 1970" would be split into 4 sentences using str.split(), and that's not what I want.
Wiki must have some sort of determination of what defines a sentence as it works when you limit the number of existence in a call (they don't break a sentence on an in-line period). Is there a way to get them individually?
Looking for a solution in JavaScript to parse a JSON excerpt string.
I ended up figuring out a work-around. Using exsentences, I made 10 calls, each with one more sentence than the previous call. I stored the results of each call in an array. So when the 10 calls were complete, I had 10 strings, ranging from one sentence in position 0, up to 10 sentences in the 9th position. Then I just iterated through the array, from 0 to length - 2, subtracting the string in the current position from the string at position [i + 1] (with string[i + 1].slice(string[i].length)), to get the nth string.

Accessing the last element in Perl6

Could someone explain why this accesses the last element in Perl 6
#array[*-1]
and why we need the asterisk *?
Isn't it more logical to do something like this:
#array[-1]
The user documentation explains that *-1 is just a code object, which could also be written as
-> $n { $n - 1 }
When passed to [ ], it will be invoked with the array size as argument to compute the index.
So instead of just being able to start counting backwards from the end of the array, you could use it to eg count forwards from its center via
#array[* div 2] #=> middlemost element
#array[* div 2 + 1] #=> next element after the middlemost one
According to the design documents, the reason for outlawing negative indices (which could have been accepted even with the above generalization in place) is this:
The Perl 6 semantics avoids indexing discontinuities (a source of subtle runtime errors), and provides ordinal access in both directions at both ends of the array.
If you don't like the whatever-star, you can also do:
my $last-elem = #array.tail;
or even
my ($second-last, $last) = #array.tail(2);
Edit: Of course, there's also a head method:
my ($first, $second) = #array.head(2);
The other two answers are excellent. My only reason for answering was to add a little more explanation about the Whatever Star * array indexing syntax.
The equivalent of Perl 6's #array[*-1] syntax in Perl 5 would be $array[ scalar #array - 1]. In Perl 5, in scalar context an array returns the number of items it contains, so scalar #array gives you the length of the array. Subtracting one from this gives you the last index of the array.
Since in Perl 6 indices can be restricted to never be negative, if they are negative then they are definitely out of range. But in Perl 5, a negative index may or may not be "out of range". If it is out of range, then it only gives you an undefined value which isn't easy to distinguish from simply having an undefined value in an element.
For example, the Perl 5 code:
use v5.10;
use strict;
use warnings;
my #array = ('a', undef, 'c');
say $array[-1]; # 'c'
say $array[-2]; # undefined
say $array[-3]; # 'a'
say $array[-4]; # out of range
say "======= FINISHED =======";
results in two nearly identical warnings, but still finishes running:
c
Use of uninitialized value $array[-2] in say at array.pl line 7.
a
Use of uninitialized value in say at array.pl line 9.
======= FINISHED =======
But the Perl 6 code
use v6;
my #array = 'a', Any, 'c';
put #array[*-1]; # evaluated as #array[2] or 'c'
put #array[*-2]; # evaluated as #array[1] or Any (i.e. undefined)
put #array[*-3]; # evaluated as #array[0] or 'a'
put #array[*-4]; # evaluated as #array[-1], which is a syntax error
put "======= FINISHED =======";
will likewise warn about the undefined value being used, but it fails upon the use of an index that comes out less than 0:
c
Use of uninitialized value #array of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to something meaningful.
in block <unit> at array.p6 line 5
a
Effective index out of range. Is: -1, should be in 0..Inf
in block <unit> at array.p6 line 7
Actually thrown at:
in block <unit> at array.p6 line 7
Thus your Perl 6 code can more robust by not allowing negative indices, but you can still index from the end using the Whatever Star syntax.
last word of advice
If you just need the last few elements of an array, I'd recommend using the tail method mentioned in mscha's answer. #array.tail(3) is much more self-explanatory than #array[*-3 .. *-1].

optimised minimum value using findall/3

I am trying to optimise and find the minimum Cost of a function. The program below uses findall/3 to iterate over all possible options of values which are generated from using the clpfd library provided by SWI-Prolog.
There are several Cost values that are generated using this program below which are gathered into a list. I know that in order to get the minimum value I can simply use the min_list/2 predicate available. However, what I want is that once the program finds a certain value, which is currently the minimum, while computing other options, if the value turns out to be greater than the minimum value, its not added the list.
So essentially, I want to optimise the program so that it simply accounts for the minimum value generated by the program.
optimise(input, arguments, Cost):-
findall(Cost, some_predicate(input, arguments, Cost), List).
some_predicate(input, arguments, Cost):-
Option in input..arguments, label(Option),
find_data(Option, Value),
find_cost(Value, Cost).
The above code has been modified so that it is condensed and but fulfils the purpose of the question.
I think that findall it's not the right tool: here is some code I wrote time ago, that could help you. For instance, given
member_(X,Y) :- member(Y,X).
we can get the lower element
?- integrate(min, member_([1,2,4,-3]), M).
M = -3
I applied the usual convention to postfix with underscore a library predicate that swaps arguments, to be able to meta call it.
Just take that code as an example, paying attention to nb_setarg usage.
To see if it could work 'out-of-the-box', try:
:- [lag].
optimise(Input, Arguments, Cost):-
integrate(min, some_predicate(Input, Arguments), Cost).

can a variable have multiple values

In algebra if I make the statement x + y = 3, the variables I used will hold the values either 2 and 1 or 1 and 2. I know that assignment in programming is not the same thing, but I got to wondering. If I wanted to represent the value of, say, a quantumly weird particle, I would want my variable to have two values at the same time and to have it resolve into one or the other later. Or maybe I'm just dreaming?
Is it possible to say something like i = 3 or 2;?
This is one of the features planned for Perl 6 (junctions), with syntax that should look like my $a = 1|2|3;
If ever implemented, it would work intuitively, like $a==1 being true at the same time as $a==2. Also, for example, $a+1 would give you a value of 2|3|4.
This feature is actually available in Perl5 as well through Perl6::Junction and Quantum::Superpositions modules, but without the syntax sugar (through 'functions' all and any).
At least for comparison (b < any(1,2,3)) it was also available in Microsoft Cω experimental language, however it was not documented anywhere (I just tried it when I was looking at Cω and it just worked).
You can't do this with native types, but there's nothing stopping you from creating a variable object (presuming you are using an OO language) which has a range of values or even a probability density function rather than an actual value.
You will also need to define all the mathematical operators between your variables and your variables and native scalars. Same goes for the equality and assignment operators.
numpy arrays do something similar for vectors and matrices.
That's also the kind of thing you can do in Prolog. You define rules that constraint your variables and then let Prolog resolve them ...
It takes some time to get used to it, but it is wonderful for certain problems once you know how to use it ...
Damien Conways Quantum::Superpositions might do what you want,
https://metacpan.org/pod/Quantum::Superpositions
You might need your crack-pipe however.
What you're asking seems to be how to implement a Fuzzy Logic system. These have been around for some time and you can undoubtedly pick up a library for the common programming languages quite easily.
You could use a struct and handle the operations manualy. Otherwise, no a variable only has 1 value at a time.
A variable is nothing more than an address into memory. That means a variable describes exactly one place in memory (length depending on the type). So as long as we have no "quantum memory" (and we dont have it, and it doesnt look like we will have it in near future), the answer is a NO.
If you want to program and to modell this behaviour, your way would be to use a an array (with length equal to the number of max. multiple values). With this comes the increased runtime, hence the computations must be done on each of the values (e.g. x+y, must compute with 2 different values x1+y1, x2+y2, x1+y2 and x2+y1).
In Perl , you can .
If you use Scalar::Util , you can have a var take 2 values . One if it's used in string context , and another if it's used in a numerical context .