如何模拟core.logic中的"外连接"?

Pet*_*art 16 logic clojure minikanren clojure-core.logic

我刚刚开始使用core.logic,并且正在努力实现它我正在尝试实现一些类似于我目前专业工作的问题.然而,问题的一部分让我难过......

作为我的例子的简化,如果我有一个项目目录,其中一些仅在某些国家/地区可用,而某些项目在特定国家/地区不可用.我希望能够指定项目列表和例外,例如:

(defrel items Name Color)
(defrel restricted-to Country Name)
(defrel not-allowed-in Country Name)

(facts items [['Purse 'Blue]
              ['Car 'Red]
              ['Banana 'Yellow]])

(facts restricted-to [['US 'Car]])

(facts not-allowed-in [['UK 'Banana]
                       ['France 'Purse]])
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我宁愿不为所有国家指定允许,因为有限制的项目集相对较小,我希望能够进行一次更改以允许/排除给定的项目国家.

如何编写一个规则,为一个国家/地区提供项目/颜色列表,具有以下约束:

  • 该项目必须位于项目列表中
  • 国家/项​​目必须不在"不允许进入"列表中
  • 或者:
    • 该项目的限制列表中没有国家/地区
    • 国家/项​​目对位于限制列表中

有办法做到这一点吗?我是以完全错误的方式思考问题的吗?

Amb*_*ose 14

通常当你开始在逻辑编程中否定目标时,你需要达到非关系运算(在Prolog中切入,在core.logic中使用conda).

只应使用ground参数调用此解决方案.

(defn get-items-colors-for-country [country]
  (run* [q]
    (fresh [item-name item-color not-country]
      (== q [item-name item-color])
      (items item-name item-color)
      (!= country not-country)

      (conda
        [(restricted-to country item-name)
         (conda
           [(not-allowed-in country item-name)
            fail]
           [succeed])]
        [(restricted-to not-country item-name)
         fail]
        ;; No entry in restricted-to for item-name
        [(not-allowed-in country item-name)
         fail]
        [succeed]))))

(get-items-colors-for-country 'US)
;=> ([Purse Blue] [Banana Yellow] [Car Red])

(get-items-colors-for-country 'UK)
;=> ([Purse Blue])

(get-items-colors-for-country 'France)
;=> ([Banana Yellow])

(get-items-colors-for-country 'Australia)
;=> ([Purse Blue] [Banana Yellow])
Run Code Online (Sandbox Code Playgroud)

完整解决方案