There is this block of code in my program that I simplified here, while the initial value of previoF is false the program doesn't print "s1" and only prints "s0".
I tried looking at it in various ways, and I don't get what is wrong with the code.
Could it be that I am not writing the if statement the right way somehow ?
previoF = false
for f in filter(x -> endswith(x, "VMSource.vm"), readdir())
open(f,"a") do file
for ln in eachline(open(f))
if (previoF==false)
if(contains(ln,"Add"))
println("s1")
end
previoF=true
else
if(contains(ln,"Add"))
println("s0")
end
previoF=false
end
end
end
end
Related
This is the method that processes an input string
def process(input) do
list=String.split(input, "\n")
f3=fn(a) ->
String.split(a," ")
end
list=Enum.map(list, f3)
func3=fn(n) ->
length(n)==3
end
func2=fn(n) ->
length(n)<=2
end
system=for x <-list, func3.(x), do: x
input=for y <- list, func2.(y), do: y
input=Enum.slice(input,0..length(input)-2)
output=""
output(input,output, system)
end
This is the output function that uses recursion to edit a string and eventually return its value
def output(input, output, system) do
cond do
length(input)==0 ->
output
true ->
[thing|tail]=input
if length(thing)==2 do
output=output<>"From "<>Enum.at(thing, 0)<>" to "<>Enum.at(thing,1)<>" is "<>Integer.to_string(calculate(thing, system))<>"km\n"
output(tail, output, system)
end
if length(thing)==1 do
if Enum.at(thing,0)=="Sun" do
output=output<>"Sun orbits"
output(tail, output, system)
else
output=output<>orbits(thing, system)<>" Sun"
output(tail, output, system)
end
end
output(tail, output, system)
end
end
As you can see when the input is an empty list it should return the output string. Using inspect shows that the output string does indeed have the correct value. Yet when the function is called in process(), it only returns the empty string, or nil.
Any help is appreciated, I am new to elixir so apologies if my code is a bit messy.
This could be a case where using pattern matching in the function head will let you avoid essentially all of the conditionals. You could break this down as:
def output([], message, _) do
message
end
def output([[from, to] | tail], message, system) do
distance = Integer.to_string(calculate(thing, system))
new_message = "#{message}From #{from} to #{to} is #{distance} km\n"
output(tail, new_message, system)
end
def output([["Sun"] | tail], message, system) do
output(tail, "Sun orbits #{message}", system)
end
def output([[thing] | tail], message, system) do
new_message = "#{message}#{orbits([thing], system)} Sun"
output(tail, new_message, system)
end
This gets around some of the difficulties highlighted in the comments: reassigning output inside a block doesn't have an effect, and there aren't non-local returns so after an if ... end block completes and goes on to the next conditional, its result is lost. This will also trap some incorrect inputs, and your process will exit with a pattern-match error if an empty or 3-element list winds up in the input list.
I've renamed the output parameter to the output function to message. This isn't required – the code will work fine whether or not you change it – but I found it a little confusing reading through the function whether output is a function call or a variable.
I am trying to implement Fermat Attack in maple but it is giving me an error stating that Error,(unexpected. Super beginner with Maple so if anyone who does have some experience could help, it would be much appreciated.
Also, I am trying to factor an integer that is 125 digits long. Does anyone know any efficient algorithm in Maple or any other program that can handle and factor such a large integers?
FermatAtttack:=proc(n::And(posint,odd), maxnumsteps::posint:=10^7,(numsteps::truefalse:=false))
local x, k, r, i, y:
x:=isqrt(n);
if x^2 < n then
x:= x+1
end if;
k:=2*x+1;
r:=x^2-n;
for i to maxnumsteps while not issqr(r) do
r:=r+k;
k:=k+2
end do;
if issqr(r) then
x:=(k-1)/2;
y:=isqrt(r)
else
error "%1 could not facot in %2 iteratioons", n, maxnumsteps
end if;
if not numsteps then
x-y, x+y
else
x-y, x+y, i
end if;
end proc:
You will need to use the Number Field Sieve to factor your 125-digit integer. See this guide to get started.
The error message is a simple syntax error. Your first line is probably supposed to be
FermatAtttack:=proc(n::And(posint,odd), maxnumsteps::posint:=10^7,{numsteps::truefalse:=false})
Maple uses the command "ifactor" to factor integers.
In your parameter sequence of the definition of your procedure FermatAttack, you have a round-bracketed item within the bracketed parameter declaration, and your error message is due to that.
(numsteps::truefalse:=false)
Change that to either just,
numsteps::truefalse:=false
or to,
{numsteps::truefalse:=false}
according to how you intend on calling it. The second of those is termed a keyword parameter. Here's a short illustration of the difference.
FA := proc( ns::truefalse:=false )
print(ns);
end proc:
FA();
false
FA(true);
true
FB := proc( {ns::truefalse:=false} )
print(ns);
end proc:
FB(); # getting the default value
false
FB( ns=false );
false
FB( ns=true );
true
FB( ns ); # a convenience of type truefalse keyword parameters
true
If you use the keyword parameter approach then note that the passed argument true in the next example doesn't match the keyword (which thus gets its default value).
FB( true );
false
So here is a piece of my body file. I am getting the error "words.adb:75:42: actual for "S" must be a variable".
procedure Remove_Character(S : in out Ustring; C : in Character; Successful : out Boolean) is
begin
for I in 1..length(S) loop
if Element(S, I) = C then
Delete(S, I, I);
Successful := true;
return;
end if;
end loop;
Successful := false;
end Remove_Character;
function Is_Subset(Subset : Ustring; S : Ustring) return Boolean is
Could_Remove : Boolean;
begin
for I in 1..length(Subset) loop
Remove_Character(S , Element(Subset, I), Could_Remove);
if Could_Remove = false then
return false;
end if;
end loop;
return True;
end Is_Subset;
I understand where my error is coming from. Remove_Character uses S : in out Ustring while function Is_Subset uses S : in Ustring.
My question is how do I change the variable from Remove_Character into only an in Ustring?
Sorry if this is a tad jumbled, I'm fairly new to both programming and the site.
You can't, at least not directly.
I don't know what a UString is, but I presume the Delete procedure modifies it. If you changed the declaration of S in Remove_Character to S: in Ustring, you'd presumably get an error on the call to Delete.
The simplest approach I can think of would be to make a copy of S in Is_Subset:
Copy_Of_S: UString := S;
and then pass the (modifiable) copy to Remove_Character.
By "simplest", I mean it makes the smallest change to your existing code. But you should probably consider reorganizing it. Determining whether one UString is a subset of another by modifying one of the strings doesn't seem like the best approach; I'm sure there's a more efficient way to do it.
A minor and irrelevant point: this:
if Could_Remove = false then
is better written as:
if not Could_Remove then
okay i have a file that looks like this:
2 3
6 6 22
-1 3 0
the integers in the first row are the dimensions of the matrix (not to be included in the matrix)
the rows below the dimensions are the actual matrix
i am trying to write a program that stores this matrix into a 2D array but i keep getting a runtime error when i try to read in the matrix with the nested do loop. It keeps saying "fortran runtime error: end of file" here is my code
PROGRAM addsub
IMPLICIT NONE
CHARACTER(30)::file1
INTEGER:: i,j,err1
INTEGER, DIMENSION(1)::dim1r,dim1c
REAL, ALLOCATABLE:: array1(:,:)
WRITE(*,101) "What is the first filename?"
READ(*,*) file1
OPEN (UNIT=11, FILE=file1, STATUS="OLD", ACTION="READ", IOSTAT=err1)
IF (err1 .NE. 0) THEN
WRITE(*,'(2A)')"There was an error opening ", file1
STOP
END IF
DO i=1,1,1
READ(11,*)dim1r(1),dim1c(1)
END DO
ALLOCATE(array1(dim1r(1),dim1c(1)))
REWIND(11)
DO i=1,dim1r(1),1
DO j=1,dim1c(1),1
READ(11,*) array1(i,j)
END DO
END DO
END PROGRAM addsub
The main problem is that each of your READ statements are trying to read a separate line; so you're trying to read 6 lines, and your file doesn't have that many.
There's a few ways around this:
You can try to read each number one at a time using advance='no', but that means you can't use list-directed input and need to use formatting explicitly:
DO i=1,dim1r
DO j=1,dim1c-1
READ(11,FMT='(F2.0)',advance='no') array1(i,j)
PRINT *, array1(i,j)
END DO
READ(11,FMT='(F2.0)') array1(i,dim1c)
END DO
You can use implied do loops to read an entire row at once:
DO i=1,dim1r
READ(11,*) (array1(i,j),j=1,dim1c)
END DO
Or just have read deal with it by giving it the array slice:
DO i=1,dim1r
READ(11,*) array1(i,1:dim1c)
END DO
Note another couple of things -- dim1c and dim1r don't have to be arrays; and you shouldn't REWIND after reading the header, or else you'll read the header in as data.
So a complete working version looks like this:
PROGRAM addsub
IMPLICIT NONE
CHARACTER(30)::file1
INTEGER:: i,err1
INTEGER ::dim1r,dim1c
REAL, ALLOCATABLE:: array1(:,:)
PRINT *, "What is the first filename?"
READ(*,*) file1
OPEN (UNIT=11, FILE=file1, STATUS="OLD", ACTION="READ", IOSTAT=err1)
IF (err1 .NE. 0) THEN
WRITE(*,'(2A)')"There was an error opening ", file1
STOP
END IF
DO i=1,1,1
READ(11,*)dim1r, dim1c
END DO
ALLOCATE(array1(dim1r,dim1c))
DO i=1,dim1r
READ(11,*) array1(i,1:dim1c)
END DO
DO i=1,dim1r
PRINT *, array1(i,:)
END DO
DEALLOCATE(array1)
END PROGRAM addsub
I have a large classic ASP app that I have to maintain, and I repeatedly find myself thwarted by the lack of short-circuit evaluation capability. E.g., VBScript won't let you get away with:
if not isNull(Rs("myField")) and Rs("myField") <> 0 then
...
...because if Rs("myField") is null, you get an error in the second condition, comparing null to 0. So I'll typically end up doing this instead:
dim myField
if isNull(Rs("myField")) then
myField = 0
else
myField = Rs("myField")
end if
if myField <> 0 then
...
Obviously, the verboseness is pretty appalling. Looking around this large code base, the best workaround I've found is to use a function the original programmer wrote, called TernaryOp, which basically grafts in ternary operator-like functionality, but I'm still stuck using a temporary variable that would not be necessary in a more full-featured language. Is there a better way? Some super-secret way that short-circuiting really does exist in VBScript?
Nested IFs (only slightly less verbose):
if not isNull(Rs("myField")) Then
if Rs("myField") <> 0 then
Maybe not the best way, but it certainly works... Also, if you are in vb6 or .net, you can have different methods that cast to proper type too.
if cint( getVal( rs("blah"), "" ) )<> 0 then
'do something
end if
function getVal( v, replacementVal )
if v is nothing then
getVal = replacementVal
else
getVal = v
end if
end function
I always used Select Case statements to short circuit logic in VB. Something like..
Select Case True
Case isNull(Rs("myField"))
myField = 0
Case (Rs("myField") <> 0)
myField = Rs("myField")
Case Else
myField = -1
End Select
My syntax may be off, been a while. If the first case pops, everything else is ignored.
If you write it as two inline IF statements, you can achieve short-circuiting:
if not isNull(Rs("myField")) then if Rs("myField") <> 0 then ...
But your then action must appear on the same line as well. If you need multiple statements after then, you can separate them with : or move your code to a subroutine that you can call. For example:
if not isNull(Rs("myField")) then if Rs("myField") <> 0 then x = 1 : y = 2
Or
if not isNull(Rs("myField")) then if Rs("myField") <> 0 then DoSomething(Rs("myField"))
Or perhaps I got the wrong end of the question. Did you mean something like iIf() in VB? This works for me:
myField = returnIf(isNothing(rs("myField")), 0, rs("myField"))
where returnIf() is a function like so:
function returnIf(uExpression, uTrue, uFalse)
if (uExpression = true) then returnIf = uTrue else returnIf = uFalse : end if
end function
Yeah it's not the best solution but what we use is something like this
function ReplaceNull(s)
if IsNull(s) or s = "" then
ReplaceNull = " "
else
ReplaceNull = s
end if
end function
Would that there were, my friend -- TernaryOp is your only hope.
Two options come to mind:
1) use len() or lenb() to discover if there is any data in the variable:
if not lenb(rs("myField"))=0 then...
2) use a function that returns a boolean:
if not isNothing(rs("myField")) then...
where isNothing() is a function like so:
function isNothing(vInput)
isNothing = false : vInput = trim(vInput)
if vartype(vInput)=0 or isEmpty(vInput) or isNull(vInput) or lenb(vInput)=0 then isNothing = true : end if
end function
You may be able to just use Else to catch nulls, ""s, etc.
If UCase(Rs("myField")) = "THING" then
'Do Things
elseif UCase(Rs("myField")) = "STUFF" then
'Do Other Stuff
else
'Invalid data, such as a NULL, "", etc.
'Throw an error, do nothing, or default action
End If
I've tested this in my code and it's currently working. Might not be right for everyone's situation though.