algorithmrecursionclipsexpert-system

Recursive function in CLIPS


I'm trying to do simple algorithms on clips to get familiar with the language. In this algorithm, I'm trying to make simple recursion calls to calculate the greatest common divisor, but CLIPS breaks every time I try to run it and I don't know why.

(deffunction mcd (?a ?b)
  (if (= ?a ?b) then
    (return ?a)
  else if (> ?a ?b) then
    (return (mcd (- ?a ?b) ?b))
  else
    (return (mcd ?a (- ?b ?a)))
  )
)

If I enter (mcd 3 3) it works but if a != b CLIPSIDE crashes.


Solution

  • You are missing a pair of parenthesis in your else if (...) thus your conditions are not evaluated correctly and your code goes into an infinite recursion.

    Either remove all the else keywords. They are not necessary because you are returing anyways when the condition in the if is met ...

    (deffunction mcd (?a ?b)
      (if (= ?a ?b) 
        then
        (return ?a)
      )
    
      ;when you arrive here, you know that a != b, 
      (if (> ?a ?b)
        then
        (return (mcd (- ?a ?b) ?b))
      )
    
      ;when you arrive here, you know a < b
      (return (mcd ?a (- ?b ?a)))
    )
    

    Or fix your parenthesis

    (deffunction mcd (?a ?b)
      (if (= ?a ?b) then
        (return ?a)
      else 
        (if (> ?a ?b) then
          (return (mcd (- ?a ?b) ?b))
        else
          (return (mcd ?a (- ?b ?a)))
        )
      )
    )