clojureconstraint-programminglogic-programmingclojure-core.logicminikanren

Finding similar sets with clojure's core.logic / minikanren


this is my first question on Stack Overflow.

I’m new to logic programming and are trying to evaluate if it can be used to solve some matching problems I’m working on.

Problem:

Lets say we have a set A that looks like this.

A = {1, 2, 3, 4}

And then we have some other sets that looks like this.

B = {1, 2}
C = {3, 5, “banana"} 
D = {2, 3, 4}

The problem I’m trying to solve is,

"Find me the set that share the most members with set A, compared to the other sets we know about."

The answer in this case should be set D, because it shares three members with set A. Compared to the other sets that only share two and one member with A.

Question 1:

Can Logic Programming solve this types of problems?

Question 2:

If it can, how would you do it in for example Clojure’s core.logic?


Solution

  • Qeshi

    The following shows getting the best fit result using clojure.set:

    (ns
      sample.sandbox
      (:require [clojure.set :as set])
      )
    
    (def A #{ 1, 2, 3, 4})
    (def B #{1, 2})
    (def C #{3, 5, "banana"})
    (def D #{2, 3, 4})
    
    (defn best-fit-set
      [control & sets]
      (apply max-key count (map #(set/intersection control %) sets )))
    
    (best-fit-set A B C D) => #{4 3 2}