building a list with Recursion with Prolog - recursion

I have a recursive predicate that builds a list like it's suposed to, the problem is that eventually it starts 'debuilding it' and gives me an empty list, the linha predicate is ok, it gives a value to Vel, and Or.
actualizarveiculos(_,[],D).
actualizarveiculos(Tempo,[(X,Y)|RestoVeiculos],NovaVeiculos):-
linha(Y,Or,Vel),
faz_andar_veic(Or,(X,Y),C,mod(Tempo,Vel)),
append(NovaVeiculos,[C],D),
actualizarveiculos(Tempo,RestoVeiculos,D).
faz_andar_veic(90,(X,Y),(X+1,Y),0).
faz_andar_veic(270,(X,Y),(X-1,Y),0).
faz_andar_veic(_,(X,Y),(X,Y),C):-
C=\=0.
the trace

You need to change it as follows:
actualizarveiculos(_,[],D, D).
actualizarveiculos(Tempo,[(X,Y)|RestoVeiculos],Acc, Res):-
Or is 2,
Vel is 2,
faz_andar_veic(Or,(X,Y),C,mod(Tempo,Vel)),
append(Acc,[C],D),
actualizarveiculos(Tempo,RestoVeiculos,D, Res).
faz_andar_veic(90,(X,Y),(X+1,Y),0).
faz_andar_veic(270,(X,Y),(X-1,Y),0).
faz_andar_veic(_,(X,Y),(X,Y),C):-
C=\=0.
Test run:
[debug] ?- actualizarveiculos(5, [(-5,3), (-4,4), (-4,5)], [], Res).
Res = [ (-5, 3), (-4, 4), (-4, 5)] .
In the trace you provided you query actualizarveiculos(5, [(-5,3), (-4,4), (-4,5)], N). Since N is unbound then NovaVeiculos becomes unbound and then you do: append(NovaVeiculos,[C],D), which probably does not do what you think it does or atleast what you intended it to do. What it does is that it tries to append an unbound variable with a list and the result is unified with another unbound variable which obviously can give an infinite number of solutions, e.g.:
[debug] ?- actualizarveiculos(5, [(-5,3), (-4,4), (-4,5)], N).
N = [] ;
N = [_G3430] ;
N = [_G3430, _G3436] ;
N = [_G3430, _G3436, _G3442] ;
N = [_G3430, _G3436, _G3442, _G3448] ;
N = [_G3430, _G3436, _G3442, _G3448, _G3454] ;
N = [_G3430, _G3436, _G3442, _G3448, _G3454, _G3460] ;
N = [_G3430, _G3436, _G3442, _G3448, _G3454, _G3460, _G3466] ;
N = [_G3430, _G3436, _G3442, _G3448, _G3454, _G3460, _G3466, _G3472] ;
N = [_G3430, _G3436, _G3442, _G3448, _G3454, _G3460, _G3466, _G3472, _G3478] ;
N = [_G3430, _G3436, _G3442, _G3448, _G3454, _G3460, _G3466, _G3472, _G3478|...] ;
Hope it helps, comment if you have questions. Since you didn't provide the linha/3 predicate I just exchanged it with two unifications:
Or is 2,
Vel is 2,

Related

How is it possible to collect NLexpression in a loop?

Would you please help me that how I can collect some NLexpressions in a loop?
I Want to keep k8 and k9 for all i=1:10 as scenarios. It means in the end of the loop, Q equal to collection of k8 and k9 under each scenario ( i ). I couldn't define a matrix and put each pair of k8 and k9 in that as an element. with considering Q the code doesn't work as well.
Many thanks for your kindly help.
using JuMP,CPUTime, Distributions, Ipopt,Juniper,Cplex
n1=1; #the least of scenarios
N=4; #number of scenarios
M=20; #number of sampling
landa=0.01;
E=0.05
T0=0;
T1=2;
T2=2;
gam2=1; gam1=1;
a1=0.5; a2=0.1; a3=50; ap=25;
c0=10;
Zn=zeros(N, 4)
Q=0;
for i in n1:N
C1=rand(100:100:300);
sig=rand(0.5:0.5:2);
f(x) = cdf(Normal(0, 1), x);
#---------------------------------------------------------------------------
ALT= Model(optimizer_with_attributes(Juniper.Optimizer, "nl_solver"=>optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0),
"mip_solver"=>optimizer_with_attributes(Cplex.Optimizer, "logLevel" => 0),"registered_functions" =>[Juniper.register( :f, 1, f; autodiff = true)])
);
# variables-----------------------------------------------------------------
JuMP.register(ALT, :f, 1, f; autodiff = true);
#variable(ALT, h >= 0.001);
#variable(ALT, L >= 0.000001);
#variable(ALT, n>=2, Int);
#---------------------------------------------------------------------------
#NLexpression(ALT,k1,h/(1-f(L-sig*sqrt(n))+f(-L - sig*sqrt(n)))); # HARL1
#NLexpression(ALT,k2,(1-(1+landa*h)*exp(-landa*h))/(landa*(1-exp(-landa*h)))); #to
#NLexpression(ALT,k3,E*n+T1*gam1+T2*gam2);
#NLexpression(ALT,k8,(C1*(k1-k2+k3)));# depend on scenario
#NLexpression(ALT,k9,(((a1+a2*n)/h)*(k1)));#depend on scenario
Q=Q+k8+k9;
#-----------------------------------------------------------------------
end
You have a couple of issues in your code.
Why are you creating a new model every loop? You cannot aggregate expressions across models like you do with Q=Q+k8+k9
You cannot add nonlinear expressions like Q=Q+k8+k9. All nonlinear expressions must occur inside macros
In general, you are not limited to the specific syntax of JuMP. You can use any Julia data structures to help. In the code below, I just push expressions into a vec
I haven't tested, so there might be typos etc, but this should point you in the right direction:
using JuMP, Distributions
E, landa, T1, T2, gam1, gam2, a1, a2 = 0.05, 0.01, 2, 2, 1, 1, 0.5, 0.1
ALT = Model()
f(x) = cdf(Normal(0, 1), x)
JuMP.register(ALT, :f, 1, f; autodiff = true)
#variable(ALT, h >= 0.001)
#variable(ALT, L >= 0.000001)
#variable(ALT, n >= 2, Int)
k8, k9 = Any[], Any[]
for i in 1:4
C1 = rand(100:100:300)
sig = rand(0.5:0.5:2)
k1 = #NLexpression(ALT, h / (1 - f(L - sig * sqrt(n)) + f(-L - sig * sqrt(n))))
k2 = #NLexpression(ALT, (1 - (1 + landa * h) * exp(-landa * h)) / (landa * (1 - exp(-landa * h))))
k3 = #NLexpression(ALT, E * n + T1 * gam1 + T2 * gam2)
push!(k8, #NLexpression(ALT, C1 * (k1 - k2 + k3))
push!(k9, #NLexpression(ALT, k9, (a1 + a2 * n) / h * k1)
end
Q = #NLexpression(ALT, sum(k for k in k8) + sum(k for k in k9))

Prolog tail recursive helper predicate for power

I am trying to make a tail recursive helper for power predicate in Prolog. So far I have this but when testing I get a message saying there is a breakpoint when trying to call helper predicate. What am I doing wrong? Ty for the help.
trpow(Base, Exp, Res) :- trpow_helper(Base, Exp, 1, Res).
trpow_helper(_, 0, Acc, Acc).
trpow_helper(Base, Exp, Acc, Res) :-
Exp > 0,
Decexp is Exp - 1,
Acc1 is Acc * Base,
Res = Acc1,
trpow_helper(Base, Decexp, Acc1, Res).
Based on your code,
trpow(Base, Exp, Res) :- trpow_helper(Base, Exp, 1, Res).
trpow_helper(_, 0, Acc, Acc):- !. /*Cut to avoid bt to second clause*/
trpow_helper(Base, Exp, Acc, Res) :-
Exp > 0,
Decexp is Exp - 1,
Acc1 is Acc * Base, /*removed Res = Acc1, not needed*/
trpow_helper(Base, Decexp, Acc1, Res).
It now works !
Using CLP such as that in swi-prolog:
:- use_module(library(clpfd)).
trpow(Base, Exp, Res) :- trpow_helper(Base, Exp, 1, Res).
trpow_helper( _, Exp, Acc, Acc):- Exp #= 0.
trpow_helper(Base, Exp, Acc, Res) :-
Exp #> 0,
Decexp #= Exp - 1,
Acc1 #= Acc * Base,
trpow_helper(Base, Decexp, Acc1, Res).
?- trpow(1, E, 1).
E = 0 ;
E = 1 .
?- trpow(2, E, 4).
E = 2 .
?- trpow(2, E, 8).
E = 3 .
?- trpow(B, 3, 8).
B = 2 .
?- trpow(B, E, 8).
B = 8,
E = 1 ;
B = 2,
E = 3 ;
...
After which, more solutions that doesn't instanciate B. In fact it loops forever.

How to calculate the convolution of a function with itself multiple times in Wolfram?

Excuse me I am new to Wolfram. I have seen people asking questions about how to do convolution of a function with itself in Wolfram. However, I wonder how to do it multiple times in a loop. That is to say I want to do f20* i.e. f*f*f*f*....f totaling 20 f. How to implement it?
Here is my thinking. Of course do not work....
f[x_] := Piecewise[{{0.1`, x >= 0 && x <= 10}, {0, x < 0}, {0, x > 10}}];
g = f;
n = 19;
For[i = 1, i <= n, i++, g = Convolve[f[x], g, x, y]]; Plot[
g[x], {x, -10, n*10 + 10}, PlotRange -> All]
Could anybody help me?
My new code after revising agentp's code
f[x_] := Piecewise[{{0.1, x >= 0 && x <= 10}, {0, x < 0}, {0,x > 10}}];
n = 19;
res = NestList[Convolve[#, f[x], x, y] /. y -> x &, f[x], n];
Plot[res, {x, -10, (n + 1)*10 + 10}, PlotRange -> All,PlotPoints -> 1000]
My buggy image
maybe this?
Nest[ Convolve[#, f[x], x, y] /. y -> x &, f[x] , 3]
If that's not right maybe show what you get by hand for n=2 or 3.
res = NestList[ Convolve[#, f[x], x, y] /. y -> x &, f[x] , 10];
Plot[res, {x, 0, 100}, PlotRange -> All]
this gets very slow with n, I don't have the patience to run it out to 20.
Your approach is nearly working. You just have to
make sure to copy f by value before entering the loop, because otherwise you face infinite recursion.
Assign the result of Convolve to a function which takes a parameter.
This is the code with the mentioned changes:
f[x_] := Piecewise[{{0.1, x >= 0 && x <= 10}, {0, x < 0}, {0, x > 10}}];
g[x_] = f[x];
n = 20;
For[i = 1, i <= n, i++, g[y_] = Convolve[f[x], g[x], x, y]];
Plot[g[x], {x, -10, n*10 + 10}, PlotRange -> All]
Edit: While this works, agentp's answer is more consise and i suspect also faster.

Creating an iterative function in SML

I've been stuck on this problem for a while now, and can't think of how to solve it.
Consider the following function f : N → N .
f(0) = 2, f(1) = 0, f(2) = 3,
f(n) = 3f(n-3) + 2f(n-2) - f(n-1) for n≥3.
Define an iterative version of f.
I know my solution should look something like this
fun myFun 0 = 2
| myFun 1 = 0
| myFun 2 = 3
| myFun n =
let
(* code *)
in
funHelp(3,2,0,n)
end ;
I know iterative functions are only suppose to use one recursive call, while letting the arguments do all the work. I can't figure out how to do it with this problem, though! Any help would be much appreciated!
I assume this is homework, so I just give you a partial solution:
fun f n =
let
fun iter(0, n0, n1, n2) = n0
| iter(1, n0, n1, n2) = n1
| iter(2, n0, n1, n2) = n2
| iter(n, n0, n1, n2) = iter(n - 1, n1, n2, ???)
in
iter(n, 2, 0, 3)
end
Filling in the ??? shouldn't be too hard.
fun funHelp 0 = (2,0,3)
| funHelp n = let val (x,y,z) = funHelp n - 1
in
(y,z,(3 * x) + (2 * y) - z)
end
fun myFun n = let val (x,_,_) = funHelp n
in
x
end
This should do what you seem to want, if a bit messily.

How could one write Duff's device in F#?

I am writing a very performance intense program and have been using C, but somebody told me how cool functional programming is, so I've decided to rewrite it in F#.
Anyway, the particular function I am having a hard replicating the algorithm in F# is Duff's device. Instead of the typical iteration, it unwinds the loop so it can copy 8 bytes per iteration instead of just one.
void copy_memory( char* to, char* from, size_t count ) {
size_t n = (count+7)/8;
switch( count%8 ) {
case 0: do{ *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
}while(--n>0);
}
}
This takes advantage of case fallthrough and the ability to jump to the middle of a loop in C, which, as far as I can tell, are unfortunately features that F# seems to be missing.
I read some stuff on MSDN, and figured that F#'s match feature would be the closest I could get to C's switch. So, I started to write this bit of code
open System.Reflection
let copyMemory (pTo : Pointer) (pFrom : Pointer) length =
let n = (length + 7) / 8
match n % 8 with
| 0 ->
and then I couldn't figure out what to do. It wouldn't let me start a loop here and end it in another case.
Is there something in F# that I can use to do case fall-through and jump into the middle of a loop? If you can do that for me, I think I can figure out the rest myself.
Here's the idiomatic way to fiddle memory in F# :-)
#nowarn "9" //stop telling me I'm going to break something
open Microsoft.FSharp.NativeInterop
let inline (~+) ptr = NativePtr.add ptr 1
let rec copyMemory src dest = function
| 0 -> ()
| n ->
NativePtr.read src |> NativePtr.write dest
copyMemory +src +dest (n - 1)
But this is probably more in the spirit of Duff's
let inline (+>) s d =
NativePtr.read !s |> NativePtr.write !d
s:= NativePtr.add !s 1
d:= NativePtr.add !d 1
let copyMemory src dst count =
let n = ref ((count + 7) / 8)
let s, d = ref src, ref dst
let
rec case_0() = s +> d; case_7()
and case_7() = s +> d; case_6()
and case_6() = s +> d; case_5()
and case_5() = s +> d; case_4()
and case_4() = s +> d; case_3()
and case_3() = s +> d; case_2()
and case_2() = s +> d; case_1()
and case_1() = s +> d; decr n; if !n > 0 then case_0()
match count % 8 with
| 7 -> case_7() | 6 -> case_6()
| 5 -> case_5() | 4 -> case_4()
| 3 -> case_3() | 2 -> case_2()
| 1 -> case_1() | _ -> case_0()
But seriously
System.Buffer.BlockCopy(src, 0, dest, 0, count)
There are no labels in F#. You can however unroll your loop another way.
let copy (dst : nativeptr<byte>) (src : nativeptr<byte>) count =
let mutable s = src
let mutable d = dst
for n in 1 .. count / 8 do
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
for n in 1 .. count % 8 do
NativePtr.read s |> NativePtr.write d
s <- NativePtr.ofNativeInt(NativePtr.toNativeInt s + nativeint 1)
d <- NativePtr.ofNativeInt(NativePtr.toNativeInt d + nativeint 1)
On a related note, NativePtr.add will call sizeof on nativeptr so I casted to nativeint above.

Resources