Frage

I am trying to sum a list of numbers in Jess, but I am not sure about how to go for it:

(deffunction sumAll ($?n) (return (+ ?n)))

(sumAll 1 2 3)

The above code doesn't work. How should I do it?

War es hilfreich?

Lösung

Here are two ways to do it. You could do a one-liner by building a function call as a string and making the parser re-parse it:

(deffunction sumAll($?args)
    (eval (str-cat "(+ " (implode$ ?args) ")" )))

Or you could do the iteration explicitly.

(deffunction sumAll($?args)
    (bind ?sum 0)
    (foreach ?num ?args
        (bind ?sum (+ ?sum ?num))))

The second one is probably going to be more efficient.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top