clojurelogic-programmingclojure-core.logic

What syntax core.logic matche, defne pattern matching constructs use?


Some of core.logic constructs (matcha, matche, matchu, defne, fne) use pattern matching expressions as body and can be used such as:

(run* [q]
  (fresh [a o]
    (== a [1 2 3 4 5])
    (matche [a]
            ([ [1 2 . [3 4 5] ]]
             (== q "first"))
            ([ [1 2 3 . [4 5] ]]
             (== q "second"))
            ([ [1 . _] ]
             (== q "third")))))
;=> ("first" 
;    "second"
;    "third")

(example from Logic-Starter wiki)

But I can't find specification of syntax for pattern matching in core.logic documentation. What is this syntax? Maybe I can find it in some minikanren docs or books?


Solution

  • I'll do my best to answer here. Intel from Ambrose Bonnaire-Sergeant's notes, which is the only place I could find that had any real documentation on the subject. My suspicion is that a lot of the syntax can be found buried in the research papers upon which core.logic is based, but as those are 270-page dissertations I didn't think they'd make a great reference.

    What is difference between matched variables prefixed with ? and without it?

    Variables prefixed with ? are implicitly declared instead of needing to be declared as an argument to fresh. In all other regards they behave the same.

    Is there any other destructing constructs in addition to lists with . (similar to & in clojure)?

    No, there are no other missing pieces of magical syntax for destructuring.

    Will [_ _] match only sequences with two elements?

    Yes.

    Is it possible to destruct maps?

    Not really. There's a good long-form article on the subject you can read here, but essentially maps and map-like structures have not historically been a subject of focus for the solvers that provide the theoretical underpinnings for core.logic and its ilk. If you're interested in logic solving on maps, probably the best tool you have at your disposal is featurec. To quote the documentation:

    (featurec x fs)

    Ensure that a map contains at least the key-value pairs in the map fs. fs must be partially instantiated - that is, it may contain values which are logic variables to support feature extraction.