Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell execution sequence

Tags:

haskell

can anybody help me understand this code

solve s | s == 0 = Nothing
        | s == 1 = Just 1
        | otherwise = 
          check [solve (s-(x*2)) | x <- [1..9]]

 check x = case x of
           []           -> Nothing
           (Nothing:xs) -> check xs
           (x:xs)       -> x    

why this gives stack over flow when i tried to run it with even value, and is there any way in haskell where i can debug and see the actual value of the running program , like in eclipse we do ?

thanks

like image 833
dinsim Avatar asked May 22 '26 04:05

dinsim


2 Answers

At least with GHCi, there's no way to "step" through code (Edit: no longer true, see comment below), but you can certainly add debug statements using Debug.Trace. In other words if you wanted to check all the recursive calls to solve you could say:

check [trace ("solving for " ++ show (s-(x*2)))) (solve (s-(x*2))) | x <- [1..9]]

There are cleaner ways to write that but that just illustrates the idea.

In this particular case, the reason it recurses infinitely is that the base cases of solve will never be reached. solve 2 for example, resolves to check [solve 0, solve -2, solve -4 ..., solve -16] and solve -2 resolves to check [solve -4, solve -6, ...] etc.

like image 61
Dan Avatar answered May 23 '26 20:05

Dan


Stack overflow suggests an infinite recursion. Branching on the otherwise case of "solve" is not guaranteed to terminate. I'm not sure what the code is supposed to be doing here, so I cannot suggest a fix. Hope that helps!

like image 37
CBFraser Avatar answered May 23 '26 19:05

CBFraser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!