Basic logical programming in Scala

I have a funny little problem when presented with a logical suggestion:

Rule 1. A, B and C are unique, and are numbers from 1 to 3 (so every number is used).
Rule 2. B < 2
Rule 3. C > 2

Now (assuming that this quick example that I just came up with really checks: P), it's easy to see

A = 2
B = 1
C = 3

But this is a very contrived example.

How about if you have 20 (or ten thousand) rules and they overlap. Suppose there is a valid single answer, and you somehow have access to the rules (say, this is a list of predicates).

Is there a pleasant, general, intuitive solution? I know that Prolog can solve the problem with some libraries, but my attempts have been futile. I know that I can just go over all the permutations in a range and then manually check if they comply with the rules. But that seems pretty lame.

+3
3

1, , , :

val all = (1 to 3).permutations

:

val rule2 = (a: Int, b: Int, c: Int) => b < 2
val rule3 = (a: Int, b: Int, c: Int) => c > 2

, :

val solutions = all.
  filter(i => rule2(i(0), i(1), i(2))).
  filter(i => rule3(i(0), i(1), i(2))).
  toList

solutions.toList :

List(Vector(2, 1, 3))

, , , (, rule3 , rule2).

foldLeft() :

val rules = List(rule2, rule3)

rules.
  foldLeft(all)((solutionsSoFar, rule) => 
    solutionsSoFar.filter(s => 
      rule(s(0), s(1), s(2))
    )
  )

Drools

Drools -. , DSL.

+4

. java . JaCoP. scala DSL, Prolog. SENDMOREMONEY: http://www.hakank.org/jacop/SendMoreMoney.scala

+3

You may be interested in this blog, where the author shows in a three-page article how to do logical programming in Scala:

http://ambassadortothecomputers.blogspot.com/feeds/posts/default?alt=rss

+2
source

All Articles