devoured elysium
devoured elysium

Reputation: 105067

Summing a list of numbers in Jess

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?

Upvotes: 1

Views: 286

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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.

Upvotes: 2

Related Questions