문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top