Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I de-structure a map in core.logic?

I believe I am having trouble destructuring a map in core.logic. I have the following code:

... used clojure.core.logic 
... required clojure.core.logic.arithmetic as logic.arithmetic. 

(def hand ({:rank 9, :suit :hearts} 
           {:rank 13, :suit :clubs} 
           {:rank 6, :suit :spades} 
           {:rank 8, :suit :hearts} 
           {:rank 12, :suit :clubs}))

(run* [q]
  (fresh [v w x y z]  ;;cards
    (== q [v w x y z])
    (membero v hand)
    (membero w hand)
    (membero x hand)
    (membero y hand)
    (membero z hand)
    (fresh [a b c d e]  ;;ranks
      (== {:rank a} v)
      (== {:rank b} w)
      (== {:rank c} x)
      (== {:rank d} y)
      (== {:rank e} z)
      (logic.arithmetic/>= a b)
      (logic.arithmetic/>= b c)
      (logic.arithmetic/>= c d)
      (logic.arithmetic/>= d e))
    (distincto q)))

It returns the empty list (), indicating that it found no matches. I believe it is a problem in the (== {:rank a} v) portion of the code. I am attempting to simply return q, where q is a vector of the maps in :rank descending order.

like image 957
Stephen Cagle Avatar asked Jan 17 '26 18:01

Stephen Cagle


1 Answers

A much more concise solution can now be written using the latest core.logic release 0.8.3:

(ns cards
  (:refer-clojure :exclude [==])
  (:use [clojure.core.logic])
  (:require [clojure.core.logic.fd :as fd]))

(def hand
  [{:rank 9, :suit :hearts} 
   {:rank 13, :suit :clubs} 
   {:rank 6, :suit :spades} 
   {:rank 8, :suit :hearts} 
   {:rank 12, :suit :clubs}])

(defn ranko [card rank]
  (featurec card {:rank rank}))

(run* [v w x y z :as q]
  (permuteo hand q)
  (fresh [a b c d e]
    (ranko v a) (ranko w b) (ranko x c)
    (fd/>= a b) (fd/>= b c)
    (ranko y d) (ranko z e)
    (fd/>= c d) (fd/>= d e)))
like image 115
dnolen Avatar answered Jan 21 '26 09:01

dnolen