How function If ... then ... else works?

42 views
Skip to first unread message

Руслан Сорокин

unread,
May 3, 2024, 4:41:26 AMMay 3
to CLIPSESG
Dear CLIPS users and team!
Please, explain me how this function works.

(deffunction find-first (?x ?y)
(println ?x "," (nth$ 1 ?y) "," (eq ?x (nth$ 1 ?y)))
(if (= (length$ ?y) 0)
then FALSE
else if (eq ?x (nth$ 1 ?y))
then ?y
else
(find-first ?x (rest$ ?y))))

CLIPS> (find-first b (create$ a b c))
b,a,FALSE
b,b,TRUE
b,c,FALSE
b,nil,FALSE
FALSE
CLIPS> 

From documentation:
"..The return value of the if function is the value of the last <expression> or
<action> evaluated."

Sincerely,
  Ru.

CLIPS Support

unread,
May 3, 2024, 12:49:44 PMMay 3
to CLIPSESG
Symbols including if, then, and else can be placed within the then and else portions of the if function, so both of these function calls are valid syntax:

                   CLIPS (6.4.1 4/8/23)
CLIPS> (if TRUE then if else then)
if
CLIPS> (if FALSE then if else then)
then
CLIPS>


If your deffunction, the 2nd use of the symbol if is treated as a symbol, not a function call, because it is not preceded by a '('. If you correct this mistake, your function will work properly:

CLIPS>
(deffunction find-first (?x ?y)

   (if (= (length$ ?y) 0)
      then FALSE
      else (if (eq ?x (nth$ 1 ?y))
then ?y
      else (find-first ?x (rest$ ?y)))))

CLIPS> (find-first b (create$ a b c))
(b c)
CLIPS> 

Руслан Сорокин

unread,
May 5, 2024, 1:53:36 PMMay 5
to CLIPSESG
Plague on my head! Certainly! Simultaneous programming in Python, Javascript, Java, Clojure and CLIPS is contraindicated in old age :)
Thanks for your patience and forbearance, Gary!

пятница, 3 мая 2024 г. в 19:49:44 UTC+3, CLIPS Support:
Reply all
Reply to author
Forward
0 new messages