R: agrep error when replacing string with another string - string

after a lot of trial/error and the search function I am still somewhat clueless about an I-thought-simple-thing (as always, hrmpf):
I have a column in a data frame x$question and within that column, there is an expression 'A/V' every once in a while, and I simply want it to be changed to 'A / B'.
I tried a little here and there, and thought this should work:
x$question[agrep('A/V',x$question)]<-'A / B'
but I get the error:
In `[<-.factor`(`*tmp*`, agrep('A/V', :
invalid factor level, NAs generated
or I could do this
agrep('A/V','A / B', x$question).
But here I get the error:
Error in .amatch_bounds(max.distance) :
match distance components must be non-negative
Since I am quite out of ideas, I would be very thankful, if you had a suggestions, or maybe an even simpler way of replacing a string with another string.

Does this work?
gsub("A/V","A/B",x$question)
Example:
x<-c("A/V", "A/V", "A/V")
x<-gsub("A/V","A/B",x)
>x
[1] "A/B" "A/B" "A/B"
Note: You can use ifelse for that too.
> ifelse(x=="A/B","A/V",x)
[1] "A/V" "A/V" "A/V"

Related

How can i convert a BitString into a String in Elixir?

I have a function that receives a list of strings and concatenates each string into a new string, i do that using Enum.join. But when i try this operation, i get the following error:
** (Protocol.UndefinedError) protocol Enumerable not implemented for "int main(){return 2;}" of type BitString. This protocol is implemented for the following type(s): Date.Range, File.Stream, Function, GenEvent.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Range, Stream
My way around this was trying to convert the BitString into a String, but i can't find anything for doing this in Elixir's documentation.
My other solution was trying to not get that BitString at all but i don't even know why i'm getting that BitString to begin with.
The process i'm doing is to receive a list like this: [{"int main(){return 2;}", 1}]
Then i make a list but only using the string text=Enum.map(words, fn {string, _} -> string end)
I tried printing the result so i'm sure i'm giving the correct argument; by using IO.inspect(text), i got ["int main(){return 2;}"], which looks like a list of strings to me.
Then i pass that to a function using Enum.flat_map(text, &lex_raw_tokens(&1, line))
Inside of that function, i do
def lex_raw_tokens(program,line) when program != "" do
textString=Enum.join(program, " ")
This is where i get the error. Is there any way of turning that BitString back into a String or not get that BitString?
Sorry, i'm still learning Elixir and honestly so far it's the most dificcult lenguage i've learned and i'm having a lot of troubles with it. Also, this whole thing is part of a small C compiler i'm doing as a school proyect
You have text bound to ["int main(){return 2;}"], then you're doing an Enum.flat_map/2 over text, so inside lex_raw_tokens/2, program is bound to "int main(){return 2;}". You're then trying to do an Enum.join/2 on program, but since it's a string (which is a kind of BitString), it's not enumerable.

“P6opaque, Str” vs simple “Str” types in Perl 6

This is a follow-up to my previous question.
I am finally able to reproduce the error here:
my #recentList = prompt("Get recentList: e.g. 1 2 3: ").words || (2,4,6);
say "the list is: ", #recentList;
for #recentList -> $x {
say "one element is: ", $x;
say "element type is: ", $x.WHAT;
say "test (1,2,3).tail(\"2\") : ", (1,2,3).tail("2");
say ( (10.rand.Int xx 10) xx 15 ).map: { #($_.tail($x)); };
}
And the results are ok as long as I use the default list by just hitting return at the prompt and not entering anything. But if I enter a number, it gives this error:
Get recentList: e.g. 1 2 3: 2
the list is: [2]
one element is: 2
element type is: (Str)
test (1,2,3).tail("2") : (2 3)
This type cannot unbox to a native integer: P6opaque, Str
in block at intType.p6 line 9
in block <unit> at intType.p6 line 5
If tail("2") works, why does tail($x) fail? Also, in my original code, tail($x.Int) wouldn't correct the problem, but it did here.
This is at best a nanswer. It is a thus-far failed attempt to figure out this problem. I may have just wandered off into the weeds. But I'll publish what I have. If nothing else, maybe it can serve as a reminder that the first three steps below are sensible ones; thereafter I'm gambling on my ability to work my way forward by spelunking source code when I would probably make much faster and more reliable progress by directly debugging the compiler as discussed in the third step.
OK, the first step was an MRE. What you've provided was an E that was fully R and sufficiently M. :)
Step #2 was increasing the M (golfing). I got it down to:
Any.tail('0'); # OK
Any.tail('1'); # BOOM
Note that it can be actual values:
1.tail('1'); # BOOM
(1..2).tail('1'); # BOOM
But some values work:
(1,2).tail('1'); # OK
Step #3 probably should be to follow the instructions in Playing with the code of Rakudo Perl 6 to track the compiler's execution, eg by sticking says in its source code and recompiling it.
You may also want to try out App::MoarVM::Debug. (I haven't.)
Using these approaches you'll have the power to track with absolute precision what the compiler does for any code you throw at it. I recommend you do this even though I didn't. Maybe you can figure out where I've gone wrong.
In the following I trace this problem by just directly spelunking the Rakudo compiler's source code.
A search for "method tail" in the Rakudo sources yielded 4 matches. For my golf the matching method is a match in core/AnyIterableMethods.pm6.
The tail parameter $n clearly isn't a Callable so the pertinent line that continues our spelunking is Rakudo::Iterator.LastNValues(self.iterator,$n,'tail').
A search for this leads to this method in core/Iterator.pm6.
This in turn calls this .new routine.
These three lines:
nqp::if(
n <= 0, # must be HLL comparison
Rakudo::Iterator.Empty, # negative is just nothing
explain why '0' works. The <= operator coerces its operands to numeric before doing the numeric comparison. So '0' coerces to 0, the condition is True, the result is Rakudo::Iterator.Empty, and the Any.tail('0') yields () and doesn't complain.
The code that immediately follows the above three lines is the else branch of the nqp::if. It closes with nqp::create(self)!SET-SELF(iterator,n,f).
That in turn calls the !SET-SELF routine, which has the line:
($!lastn := nqp::setelems(nqp::list, $!size = size)),
Which attempts to assign size, which in our BOOM case is '1', to $!size. But $!size is declared as:
has int $!size;
Bingo.
Or is it? I don't know if I really have correctly tracked the problem down. I'm only spelunking the code in the github repo, not actually running an instrumented version of the compiler and tracing its execution, as discussed as the sensible step #3 for trying to figure out the problem you've encountered.
Worse, when I'm running a compiler it's an old one whereas the code I'm spelunking is the master...
Why does this work?
(*,*).tail('1') # OK
The code path for this will presumably be this method. The parameter $n isn't a Callable so the code path will run thru the path that uses the $n in the lines:
nqp::unless(
nqp::istype($n,Whatever) || $n == Inf,
$iterator.skip-at-least(nqp::elems($!reified) - $n.Int)
The $n == Inf shouldn't be a problem. The == will coerce its operands to numerics and that should take care of $n being '1'.
The nqp::elems($!reified) - $n.Int shouldn't be a problem either.
The nqp ops doc shows that nqp::elems always returns an int. So this boils down to an int - Int which should work.
Hmm.
A blame of these lines shows that the .Int in the last line was only added 3 months ago.
So, clutching at straws, what happens if one tries:
(my int $foo = 1) - '1' # OK
Nope, that's not the problem.
It seems the trail has grown cold or rather I've wandered off the actual execution path.
I'll publish what I've got. Maybe someone else can pick it up from here or I'll have another go in a day or three...

Haskell: How to delete the same function and concatenate two lists

I am the beginner of haskell. I want to delete some same functions in the same list and concatenate the two list get together.
For example:
db1 = ["David","worksfor.isa", "IBM" ]
db2 = ["David","isa'.worksfor'", "IBM"]
db3 = ["Tom","worksfor.isa", "IBM" ]
the program can be known that "isa'.worksfor' and "worksfor.isa" is the same String. And then use "Concat" to get the new db: db1 =["David","worksfor.isa", "IBM" ] and the others: db3 = ["Tom","worksfor.isa", "IBM" ]
(map (\(a,b,c) -> concat (map(\(a',b',c') -> if ( a b == b' a') then [] else [(a,b ++ "." ++ b',c')])))) ??????
I want to "split the string, if there are ' characters, reverse it, then remove ' characters and check for equivalence"
This should be a comment, but it is far too long:
I assume you find it hard to express yourself in English. I can relate to that; I find it hard myself. However, beyond English there are two other ways to communicate here:
Using precise technical terms.
Using several, diverse examples. A single example will not suffice, and several examples which are too similar give little information.
As for option 1, you are using the wrong terminology. It is not easy for me to see how can a list with 3 items can be considered a database (as hinted by the names db1, db2). Perhaps you wanted to use a list of triples?
[ ("David","isa'.worksfor'", "IBM") ]
You are not specific about what exactly do you want to concatenate, but the term concatenation always refers to an operation that must be "additive", i.e. length(x ++ y) == length(x) ++ length(y). This does not seem to be the case in your question.
Do you want a union of two databases (lists of triples) up to equivalence?
You want the program to understand that
"isa'.worksfor'" and "worksfor.isa" are the same string
But they are not. They might be equivalent strings. You can generally do that using a map operation, like you tried, but you should note that the character ' is not an operation over strings. So a b == b' a' does nothing close to what you want - it calls the function a on the variable b, and compares this with calling the function b' over the variable a'. I can only assume you want something like "split the string, if there are ' characters, reverse it, then remove ' characters and check for equivalence" but this is completely a guesswork.
To conclude:
Please explain in detail what is the general problem you are trying to solve. Try to find the precise terms; it is difficult, but this way you can learn.
Please add different examples of input and output
Please try to explain what have you tried and where are you stuck
As a last tip, maybe you want to solve this problem in a more forgiving language than Haskell (such as JavaScript, Python, Ruby, etc.)

Detecting if a variable can be printed in Lua

I've got a variable that could be a number of types - sometimes it's a string, sometimes a number, table or bool. I'm trying to print out the value of the variable each time like this:
print("v: "..v)
with v being my variable. Problem is, when I get a value that can't be concatenated I get this error:
myscript.lua:79: attempt to concatenate a table value
I've tried changing it to this in case it manages to detect whether or not the variable can be printed:
print("v: "..(v or "<can't be printed>"))
but I had the same problem there. Is there some sort of function I can use to determine if a variable can be concatenated to a string, or a better way of printing out variables?
You can provide the values as separate arguments to print:
print("v:", v)
This would print something like
v: table: 006CE900
Not necessarily the most useful, but better than a crash if it's just for debugging purposes.
See here for information on more useful table printing.
tostring(v) works for all possible v values (including nil). So writing your line as:
print( "v: " .. tostring( v ) )
will always work.
Alternatively you could have a look at type( v ) and if its "string" print it, otherwise print something else (if that's what you want).

Help finding paths

% link(Origin,Destination,Speed,Length).
link(paris,milano,140,360).
link(paris,london,200,698).
link(berlin,atena,110,714).
link(atena,paris,90,370).
I need to write this route predicate so I get a Path from city X to city Y.
route(Origin,Destination,TrainType,Path,Length,Duration).
I am new to Prolog, so I wrote something like this. I know it's not correct:
route(Origin,Destination,TrainType,Path,Legth,Duration) :-
link(Origin,City,Len),
City \= Origin,
NewLen is Length + Len,
route(City,Destination,TrainType,Path,NewLen,Duration).
Your predicate lacks a base case, that tells it when to stop. Right now, your predicate will always call itself until it fails (or worse, loops indefinitely, depending on your link predicate). The following gives you a reverse path:
route(Goal, Goal, Path, Path). % base case
route(From, To, Path0, Path) :-
direct_link(From, Via),
route(Via, To, [From|Path0], Path).
where a direct link means you can get from A to B; I'm assuming railways are bidirectional:
direct_link(A,B) :- link(A, B, _Speed, _Length).
direct_link(B,A) :- link(B, A, _Speed, _Length).
You will need to call reverse on the path and add arguments to keep track of length and duration. I'll leave that as an exercise.

Resources