In my computer science class, we used Haskell to solve the "queens" problem, in which you should find all the possible placements for the n queens on the nxn board. This was the code that gave us:
queens n = solve n
where
solve 0 = [ [] ]
solve k = [ h:partial | partial <- solve(k-1), h <- [0..(n-1)], safe h partial ]
safe h partial = and [ not (checks h partial i) | i <- [0..(length partial)-1] ]
checks h partial i = h == partial!!i || abs(h-partial!!i) == i+1
However, the first time I entered it, I accidentally changed the order in solution k and found that it still gave the correct solution, but took much longer:
queens n = solve n
where
solve 0 = [ [] ]
solve k = [ h:partial | h <- [0..(n-1)], partial <- solve(k-1), safe h partial ]
safe h partial = and [ not (checks h partial i) | i <- [0..(length partial)-1] ]
checks h partial i = h == partial!!i || abs(h-partial!!i) == i+1
Why is this second version taking so much longer? My thought process is that the second version of recursion is at each step, while the first version of recursion is only once, and then back. This is not a homework problem, I am just curious, and I feel that it will help me better understand the language.