My recursion hang - haskell

It compiles correctly, but doesn't work.
It works for [] but if its anything else it just hang forever. test1 - ok, test 2 hang.
--Tests pour 'effectuerAchat'.
test1 = effectuerAchat achat1_1 [] == ([],achat1_1)
test2 = effectuerAchat achat1_1 [offre1_1_1_100] == ([(Commande "fournisseur1" "article1" 1 100)],Achat "article1" 0)
here is the code...
effectuerAchat a os = rfred a (offresPour a os) (achatQuantite(a)) []
where rfred a os n lc =
if os == []|| n==0
then (lc,(Achat (achatArticle(a)) n))
else
if n>=(offreQuantite(head(os)))
then let c= (Commande (offreFournisseur(head(os))) (achatArticle(a)) (offreQuantite(head(os))) (offrePrix(head(os))))
n= n-(offreQuantite(head(os)))
xs = tail(os)
in rfred a xs n (c:lc)
else let c= (Commande (offreFournisseur(head(os))) (achatArticle(a)) n (offrePrix(head(os))))
n= 0
xs = tail(os)
in rfred a xs n (c:lc)

You have an infinite loop in
let c= (Commande (offreFournisseur(head(os))) (achatArticle(a)) (offreQuantite(head(os))) (offrePrix(head(os))))
n= n-(offreQuantite(head(os)))
^^^^^
The n on the right hand side is not the n from the test above, but the n introduced on the left hand side of the binding (which shadows the one from the outer scope). If os (= offresPour achat1_1 [offre1_1_1_100]) contains more than one item, n is needed in the test
if os == []|| n==0
in the recursive call, and evaluation hangs.
Name the variable differently,
let c = ...
n' = n - ...
in rfred ... n' ...

Related

How to handle n not a multiple p in worker processes in matrix multiplication?

I am working on a problem regarding pseudocode for matrix multiplication using worker processes. w is the amount of workers, p is the amount of processors and n is the amount of processes.
The psuedocode calculates the matrix result by dividing the i rows into P strips of n/P rows each.
process worker[w = 1 to P]
int first = (w-1) * n/P;
int last = first + n/P - 1;
for [i = first to last] {
for [j = 0 to n-1] {
c[i,j] = 0.0;
for[k = 0 to n-1]
c[i,j] = c[i,j] + a[i,k]*b[k,j];
}
}
}
my question is how I would handle if n was not a multiple of P processors as can happen often where n is not divisible by p?
The simplest solution is to give the last worker all the remaining rows (they won't be more than P-1):
if w == P {
last += n mod P
}
n mod P is the remainder of the division of n by P.
Or change the calculation of first and last like this:
int first = ((w-1) * n)/P
int last = (w * n)/P - 1
This automatically takes care for the case when n is not divisible by P. The brackets are not really necessary in most languages where * and / have the same precedence and are left-associative. The point is that the multiplication by n should happen before the division by P.
Example: n = 11, P = 3:
w = 1: first = 0, last = 2 (3 rows)
w = 2: first = 3, last = 6 (4 rows)
w = 3: first = 7, last = 10 (4 rows)
This is a better solution as it spreads the remainder of the division evenly among the workers.

Crystal recursive function resulting in a signal 11 (invalid memory access)?

I wanted to test recursive functions in Crystal, so I wrote something like...
def repeat(n)
return if n < 0
# Useless line just to do something
n + 1
repeat(n - 1)
end
repeat(100_000_000)
I didn't expect this to work with either crystal recurse.cr or crystal build recurse.cr, because neither one of those can optimize for tail call recursion - as expected, both resulted in stack overflows.
When I used the --release flag, it was totally fine - and incredibly fast.
If I did the following...
NUM = 100_000
def p(n)
puts n if n % (NUM / 4) == 0
end
def recursive_repeat(n)
return if n < 0
p(n)
recursive_repeat(n-1)
end
recursive_repeat(NUM)
... everything is fine - I don't even need to build it.
If I change to a much larger number and a non-recursive function, again it's fine...
NUM = 100_000_000
def p(n)
puts n if n % (NUM / 4) == 0
end
def repeat(num)
(0..num).each { |n| p(n) }
end
repeat(NUM)
If I instead use recursion, however...
NUM = 100_000
def p(n)
puts n if n % (NUM / 4) == 0
end
def recursive_repeat(n)
return if n < 0
p(n)
recursive_repeat(n-1)
end
recursive_repeat(NUM)
...I get the following output:
100000000
Invalid memory access (signal 11) at address 0x7fff500edff8
[4549929098] *CallStack::print_backtrace:Int32 +42
[4549928595] __crystal_sigfault_handler +35
[140735641769258] _sigtramp +26
[4549929024] *recursive_repeat<Int32>:Nil +416
[4549929028] *recursive_repeat<Int32>:Nil +420 (65519 times)
[4549926888] main +2808
How does using puts like that trigger a stack overflow - especially given that it would only write 5 lines total?
Shouldn't this still be TCO?
Edit
Okay, to add to the weirdness, this works...
NUM = 100_000_000
def p(n)
puts n if n % (NUM / 4) == 0
end
def repeat(num)
(0..num).each { |n| p(n) }
end
repeat(NUM)
def recursive_repeat(n)
return if n < 0
p(n)
recursive_repeat(n-1)
end
recursive_repeat(NUM)
... but removing the call to repeat(NUM), literally keeping every other line the same, will again result in the error.

Is possible to define a random limit for a loop in JAGS?

I am trying to implement a Weibull proportional hazards model with a cure fraction following the approach outlined by Hui, Ibrahim and Sinha (1999) - A New Bayesian Model for Survival Data with a Surviving Fraction. However, I am not sure if it is possible to define a random limit for a looping in JAGS.
library(R2OpenBUGS)
library(rjags)
set.seed(1234)
censored <- c(1, 1)
time_mod <- c(NA, NA)
time_cens <- c(5, 7)
tau <- 4
design_matrix <- rbind(c(1, 0, 0, 0), c(1, 0.2, 0.2, 0.04))
jfun <- function() {
for(i in 1:nobs) {
censored[i] ~ dinterval(time_mod[i], time_cens[i])
time_mod[i] <- ifelse(N[i] == 0, tau, min(Z))
for (k in 1:N[i]){
Z[k] ~ dweib(1, 1)
}
N[i] ~ dpois(fc[i])
fc[i] <- exp(inprod(design_matrix[i, ], beta))
}
beta[1] ~ dnorm(0, 10)
beta[2] ~ dnorm(0, 10)
beta[3] ~ dnorm(0, 10)
beta[4] ~ dnorm(0, 10)
}
inits <- function() {
time_init <- rep(NA, length(time_mod))
time_init[which(!status)] <- time_cens[which(!status)] + 1
out <- list(beta = rnorm(4, 0, 10),
time_mod = time_init,
N = rpois(length(time_mod), 5))
return(out)
}
data_base <- list('time_mod' = time_mod, 'time_cens' = time_cens,
'censored' = censored, 'design_matrix' = design_matrix,
'tau' = tau,
'nobs' = length(time_cens[!is.na(time_cens)]))
tc1 <- textConnection("jmod", "w")
write.model(jfun, tc1)
close(tc1)
# Calling JAGS
tc2 <- textConnection(jmod)
j <- jags.model(tc2,
data = data_base,
inits = inits(),
n.chains = 1,
n.adapt = 1000)
I observed the below error:
Error in jags.model(tc2, data = data_base, inits = inits(), n.chains = 1, :
RUNTIME ERROR:
Compilation error on line 6.
Unknown variable N
Either supply values for this variable with the data
or define it on the left hand side of a relation.
I am not entirely certain, but I am pretty sure that you cannot declare a random number of nodes in BUGS in general, so it would not be a specific JAGS' quirk.
Nevertheless, you can get a way around that.
Since BUGS is a declarative language instead of a procedural one, it is enough to declare an arbitrary but deterministic number of nodes (let's say "large enough") and then associate only a random number of them with a distribution and with observed data, leaving the remaining nodes deterministic.
Once you have observed the maximum value of N[i] (let's say N.max), you can pass it as a parameter to JAGS and then change this code of yours:
for (k in 1:N[i]){
Z[k] ~ dweib(1, 1)
}
into this:
for (k in 1:N.max){
if (k <= N[i]){
Z[k] ~ dweib(1, 1)
} else {
Z[k] <- 0
}
}
I hope this will do the trick in your case. So please give feedback latter about it.
Needless to say, if you have some non-zero, observed data associated to a deterministic Z[k], then all hell breaks loose inside Jags...

Parse Error on input 'appendString' Haskell

Hey guys so this is a strange little error I'm getting and I'm not understand why it's giving it to me.
It says Parse Error in input 'appendString' yet I see nothing wrong with it...
I call it from an if,then else statement as follows:
createShow currentIndex (Grid {delta = d, middle = (x,y), points = g}) dir counter =
if currentIndex ==0 || dir == 2
then (appendString d (x,y) g currentIndex) ++ (createShow currentIndex+1 (Grid {delta = d, middle = (x,y), points = g}) 2 (counter+1))
else if counter == (2*d+1)
then (appendString d (x,y) g currentIndex) ++ (appendX x)
else if dir == 1
then (appendString d (x,y) g currentIndex) ++ (createShow currentIndex-1 (Grid {delta = d, middle = (x,y), points = g}) 1 (counter+1))
where createShow returns a string and so does appendString
appendString gives the error in the constructor:
appendString d (x,y) g currentIndex =
(if currentIndex == y
then "y "
else
" " ) ++ (show currentIndex) ++(rowFunction g x d 0 (x+d) 1)++ "\n"
do you see where I could have gone wrong with it?
Edit: Added entire area
Haskell if's are not like other if's in say Java or python. The biggest difference is that they are expressions unlike java or python where they are statements.
They are much closer to the condition ? res1 : res2 from C.
The correct way to write nested if's is like this:
if condition
then foo
else if condition2
then bar
else ...
You'll notice that this is horribly ugly.
That's why haskell has guards:
foo args | condition = foo
| condition2= bar
| otherwise = meh
Here we declare a function foo and if condition is true then we execute foo otherwise we proceed to condition2 and otherwise is always true. For you
createShow currentIndex (Grid {delta = d, middle = (x,y), points = g}) dir counter
| currentIndex == 0 || dir == 2 = appendString d ....
| counter == (2 * d + 1) = appendString d ....
| dir == 1 = appendString d ....
which looks much more readable.
Here's a refactoring::
createShow currentIndex grid#(Grid {delta = d, middle = (x,y), points = g}) dir counter =
prefix ++ show currentIndex ++ row ++ "\n" ++ nextLine
where
prefix = if currentIndex == y then "y " else " "
row = rowFunction g x d 0 (x+d) 1
nextLine | currentIndex == 0 || dir == 2 = createShow (currentIndex+1) grid 2 (counter+1)
nextLine | counter == (2*d+1) = appendX x
nextLine | dir == 1 = createShow (currentIndex-1) grid 1 (counter+1)
appendX x = ...
Things to notice:
Using a where clause often lets you avoid repeating parameters
The common call to appendString has been factored out, and moved to the top, and then in-lined, since it is only called once.
Use of guards in nextLine to handle a cascaded if more clearly.
The guards and form of nextLine make it clear it isn't a total function. What happens when it falls off the end?
The use of grid# to name a pattern. This way you don't need to "reconstruct" the Grid value when making the recursive calls.
One can go further. Noticing that Grid {...} and dir never change throughout the function suggests factoring those out:
createShow currentIndex (Grid {delta = d, middle = (x,y), points = g}) dir counter =
line currentIndex counter
where
line currentIndex counter =
prefix ++ show currentIndex ++ row ++ "\n" ++ nextLine currentIndex counter
prefix = if currentIndex == y then "y " else " "
row = rowFunction g x d 0 (x+d) 1
nextLine currentIndex counter
| currentIndex == 0 || dir == 2 = line (currentIndex+1) (counter+1)
| counter == (2*d+1) = appendX x
| dir == 1 = line (currentIndex-1) (counter+1)
appendX x = ...
Here, line plays the part of "carrying" around the only values that differ as the function recurses. It would be a common idiom to place those arguments at the end of what createShow takes, and thus even factor them out:
createShow :: Grid -> Int -> Int -> Int -> String
createShow (Grid {delta = d, middle = (x,y), points = g}) dir = line
where
line currentIndex counter =
prefix ++ show currentIndex ++ row ++ "\n" ++ nextLine currentIndex counter
prefix = if currentIndex == y then "y " else " "
row = rowFunction g x d 0 (x+d) 1
nextLine currentIndex counter
| currentIndex == 0 || dir == 2 = line (currentIndex+1) (counter+1)
| counter == (2*d+1) = appendX x
| dir == 1 = line (currentIndex-1) (counter+1)
appendX x = ...

Tail recursion with Groovy

I coded 3 factorial algorithms:
I expect to fail by stack overflow. No problem.
I try a tail recursive call, and convert the previous algorithm from recursive to iterative. It doesn't work, but I don't understand why.
I use trampoline() method and it works fine as I expect.
def factorial
factorial = { BigInteger n ->
if (n == 1) return 1
n * factorial(n - 1)
}
factorial(1000) // stack overflow
factorial = { Integer n, BigInteger acc = 1 ->
if (n == 1) return acc
factorial(n - 1, n * acc)
}
factorial(1000) // stack overflow, why?
factorial = { Integer n, BigInteger acc = 1 ->
if (n == 1) return acc
factorial.trampoline(n - 1, n * acc)
}.trampoline()
factorial(1000) // It works.
There is no tail recursion in Java, and hence there is none in Groovy either (without using something like trampoline() as you have shown)
The closest I have seen to this, is an AST transformation which cleverly wraps the return recursion into a while loop
Edit
You're right, Java (and hence Groovy) do support this sort of tail-call iteration, however, it doesn't seem to work with Closures...
This code however (using a method rather than a closure for the fact call):
public class Test {
BigInteger fact( Integer a, BigInteger acc = 1 ) {
if( a == 1 ) return acc
fact( a - 1, a * acc )
}
static main( args ) {
def t = new Test()
println "${t.fact( 1000 )}"
}
}
When saved as Test.groovy and executed with groovy Test.groovy runs, and prints the answer:
402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
As a guess, I would say that the JVM does not know how to optimise closures (like it does with methods), so this tail call does not get optimised out in the bytecode before it is executed
Starting with version 2.3 Groovy supports tail recursion with the #TailRecursive annotation for methods:
http://java.dzone.com/articles/groovy-goodness-more-efficient

Resources