Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top