'How recursion in scala case class(logical functions)
when I studying programming and the task in scala I crashed the problem
the error code is class type required but Bool found case class TrueBool extends Bool
I try many way but I can't matched type
sealed trait Bool
case class True[Bool]() extends Bool
case class False[Bool]() extends Bool
case class And[Bool](elem1: Bool ,elem2: Bool) extends Bool
case class Or[Bool](elem1: Bool, elem2: Bool) extends Bool
case class Neg[Bool](elem1: Bool) extends Bool
case class Imply[Bool](elem1: Bool, elem2: Bool) extends Bool
def formula(fma: Bool): Boolean = fma match {
// use recursion function and make consist of logical operation Neg, Or, And, Imply
case True() => true
case False() => false
case And(elem1, elem2) => if(formula(elem1) && formula(elem2)){
return true
}else{
return false
}
case Or(elem1, elem2) => if(formula(elem1) || formula(elem2)){
return true
}else{
return false
}
case Neg(elem1) => if( formula(elem1) ){
return false
}else{
return true
}
case Imply(elem1, elem2) => if(formula(elem1)){
if(formula(elem2)){
return true
}else{
return false
}
}else{
return false
}
}
println("** p10 **")
val fma = Imply(And(True, Or(True, False)), False)
println(formula(fma))
}
Solution 1:[1]
case class True[Bool]() extends Bool
I do not think this does what you want. You introduce a type parameter Bool, which is completely unrelated to your Bool trait.
You cannot extend a (generic) type parameter. This is the same as:
case class True[B]() extends B
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Suma |
