haskell - Stack overflow in my recursive function -
haskell - Stack overflow in my recursive function -
code here , when phone call numberof 3 or numberof integer>2 im getting error error - c stack overflow . code should alter numbers between 2^(n-2) (2^n)-1 n>2 binary , check if there consecutive 0 or not . if there dont count , if there isnt +1 .
numberof :: integer -> integer numberof = worker worker :: integer -> integer worker | (abs i) == 0 = 0 | (abs i) == 1 = 2 | (abs i) == 2 = 3 | otherwise = calculat (2^((abs i)-2)) ((2^(abs i))-2) calculat :: integer -> integer -> integer calculat ab bis | ab == bis && (checker(tobin ab)) == true = 1 | ab < bis && (checker(tobin ab)) == true = 1 + (calculat (ab+1) bis) | otherwise = 0 + (calculat (ab+1) bis) checker :: [integer] -> bool checker list | list == [] = true | 0 == head list && (0 == head(tail list)) = false | otherwise = checker ( tail list) tobin :: integer -> [integer] tobin n | n ==0 = [0] | n ==1 = [1] | n `mod` 2 == 0 = tobin (n `div` 2) ++ [0] | otherwise = tobin (n `div` 2) ++ [1]
tests :
numberof 3 answer:(5) numberof 5 (13) numberof 10 (144) numberof (-5) (13)
the problem lies definition of calculat
. have cases of ab == bis
, ab < bis
, place phone call calculat
worker
arguments 2^(abs - 1)
, 2^(abs - 2)
. since first number (ab
) larger sec (bis
), checking ab < bis
pretty silly. in otherwise status increment ab
, ensuring function never terminate. did instead mean otherwise = calculat ab (bis + 1)
?
you clean code substantially, there many places you've done things hard way, or added unnecessary clutter:
-- remove worker, having separate numberof pointless numberof :: integer -> integer numberof | i' == 0 = 0 | i' == 1 = 2 | i' == 2 = 3 -- lots of unneeded parentheses | otherwise = calculat (2 ^ (i' - 1)) (2 ^ i' - 2) -- avoid writing same look on , on 1 time again -- define local name `abs i` i' = abs calculat :: integer -> integer -> integer calculat ab bis -- remove unneeded parens -- don't need compare boolean true, utilize | ab == bis && checker (tobin ab) = 1 | ab < bis && checker (tobin ab) = 1 + calculat (ab + 1) bis -- 0 + == something, don't perform unnecessary operations | otherwise = calculat (ab + 1) bis -- pattern matching in function cleans lot , prevents -- errors calling head on empty list checker :: [integer] -> bool checker [] = true checker (0:0:_) = false checker (_:xs) = checker xs -- again, pattern matching can clean things up, , find in-line -- if statement more expressive guard. tobin :: integer -> [integer] tobin 0 = [0] tobin 1 = [1] tobin n = tobin (n `div` 2) ++ (if n [0] else [1])
haskell recursion stack-overflow
Comments
Post a Comment