Scala中的命题逻辑

时间:2017-03-08 03:09:41

标签: scala artificial-intelligence

Prop类型模仿命题句(或者更简洁地说,命题)。命题符号(变量)被编码为P(n)形式的项,其中n是整数标识符。 Interpr类型将命题解释实现为命题符号id的Scala列表(没有重复)。当且仅当n出现在i中时,命题符号P(n)在解释i中才是真实的。

写一个Scala方法含义(i:Interpr,p:Prop):布尔值,它接受解释i和命题p,如果解释根据命题逻辑的语义满足命题,则返回Scala布尔值true,并返回值false。

我很困惑如何使用模式匹配和递归来实现它。任何指导将不胜感激!

// Example case
meaning(List(1,2), And(P(1), P(2))) is true

// Example case
meaning(List(1), And(P(1), P(2))) is false




type PVar = Int

type Interpr = List[PVar]

sealed abstract class Prop
case object True extends Prop
case object False extends Prop
case class P(id: PVar) extends Prop                  // propositional         variable
case class Not(sub: Prop) extends Prop
case class Or(sub1: Prop, sub2: Prop) extends Prop   // inclusive or
case class Xor(sub1: Prop, sub2: Prop) extends Prop  // exclusive or
case class And(sub1: Prop, sub2: Prop) extends Prop
case class Impl(sub1: Prop, sub2: Prop) extends Prop // simple implication =>
case class Iff(sub1: Prop, sub2: Prop) extends Prop  // double implication <=>


sealed abstract class Answer
case object Yes extends Answer
case object No extends Answer

def meaning(i: Interpr, p: Prop): Boolean = p match {
    // solution here
}

1 个答案:

答案 0 :(得分:1)

我对你究竟需要什么感到困惑。该方法是否应该能够评估复合命题? List(1,2)到底是如何评估为真的?

但是关于使用递归进行评估的问题,我建议您查看Philip Wadler的论文 Monads进行函数式编程

http://example.com/pqr

这是在函数式语言中编写表达式求值程序的最佳示例之一。

相关问题