mk: sumo + producto — fold list to integer
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s

Sum and product over a list of ground integers via fold + intarith.
Empty list yields the identity (0 for sum, 1 for product). Recurse
combines the head with the recursively-computed tail value via
pluso-i / *o-i.

9 new tests, 481/481 cumulative.
This commit is contained in:
2026-05-08 12:14:15 +00:00
parent 4f5f8015fb
commit 064ab2900b
3 changed files with 61 additions and 0 deletions

View File

@@ -93,3 +93,19 @@
(conde
((fresh (a) (== l (list a)) (== m a)))
((fresh (a d rest-max) (conso a d l) (maxo d rest-max) (conde ((lteo-i rest-max a) (== m a)) ((lto-i a rest-max) (== m rest-max))))))))
(define
sumo
(fn
(l total)
(conde
((nullo l) (== total 0))
((fresh (a d rest-sum) (conso a d l) (sumo d rest-sum) (pluso-i a rest-sum total))))))
(define
producto
(fn
(l total)
(conde
((nullo l) (== total 1))
((fresh (a d rest-prod) (conso a d l) (producto d rest-prod) (*o-i a rest-prod total))))))

View File

@@ -0,0 +1,44 @@
;; lib/minikanren/tests/sum-product.sx — fold list to integer.
(mk-test "sumo-empty" (run* q (sumo (list) q)) (list 0))
(mk-test
"sumo-1-to-5"
(run*
q
(sumo (list 1 2 3 4 5) q))
(list 15))
(mk-test
"sumo-zeros"
(run* q (sumo (list 0 0 0) q))
(list 0))
(mk-test
"sumo-negs"
(run* q (sumo (list 5 -3 8) q))
(list 10))
(mk-test "producto-empty" (run* q (producto (list) q)) (list 1))
(mk-test
"producto-1-to-4"
(run* q (producto (list 1 2 3 4) q))
(list 24))
(mk-test
"producto-with-0"
(run* q (producto (list 5 0 7) q))
(list 0))
(mk-test
"producto-of-1s"
(run* q (producto (list 1 1 1) q))
(list 1))
(mk-test
"sum-product-pythagorean-square"
(run*
q
(fresh
(s sq2)
(sumo (list 3 4 5) s)
(producto (list 3 3) sq2)
(== q (list s sq2))))
(list (list 12 9)))
(mk-tests-run!)