0

Hmm... why does this function ends in an infinite loop when evaluating for any integer > 3?

smallestMultiple n = factors [2..n] where
factors [] = []
factors (h:xs) = h:(factors $ filter ((<)1) [div x h|x<-xs])
    where
      div x y
          |x `mod` y ==0 = x `div` y
          |otherwise = x
0

1 Answer 1

5

It appears that the main problem is that you define a local version of div:

div x y
  | x `mod` y == 0 = x `div` y
  | otherwise = x

Since bindings in where clauses (as well as in let) are recursive, the div on the right hand side of the first case refers to the same div you're defining! You can fix this by using a different name, like div':

div' x y
  | x `mod` y == 0 = x `div` y
  | otherwise = x
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.