【发布时间】:2018-11-26 20:46:57
【问题描述】:
我有以下任务需要完成。为了完成任务,我必须正确替换 cmets /*fulfill ...*/。但是我尽力了,我仍然得到一个
缺少扩展函数的参数类型匿名函数的参数类型必须是完全已知的。 (SLS 8.5) 错误。
我发现了与此错误相关的类似问题。但是,我无法为这些答案的特殊问题找到解决方案。
所以目标是检查事件是否满足属性。
我很高兴每一个提示。
这是我需要完成的代码:
import scala.collection.mutable.MutableList
abstract class Event
case class Command(cmdName: String) extends Event
case class Succeed(cmdName: String) extends Event
case class Fail(cmdName: String) extends Event
class Property(val name: String, val func: () => Boolean)
class Monitor[T] {
val properties = MutableList.empty[Property]
// (propName: String)(formula: => Boolean) was inserted by me
def property(propName: String)(formula: => Boolean) /* fulfill declaration here */ {
properties += new Property(propName, formula _)
}
var eventsToBeProcessed = List[T]()
def check(events: List[T]) {
for (prop <- properties) {
eventsToBeProcessed = events
println(prop.func())
}
}
def require(func: PartialFunction[T, Boolean]):Boolean = {
/* Fulfill body */
// This is what I came up with and what throws the compilation error
// case event:T => if (func.isDefinedAt(event)) Some(func(event)) else None
// Edit 1: Now I tried this but it prints that properties evaluate to false
var result = true
for (event <- eventsToBeProcessed){
if (func.isDefinedAt(event)){
result = result && func(event)
}
}
return result
}
}
class EventMonitor extends Monitor[Event] {
property("The first command should succeed or fail before it is received again") {
require {
case Command(c) =>
require {
case Succeed(`c`) => true
case Fail(`c`) => true
case Command(`c`) => false
}
}
}
property("The first command should not get two results") {
require {
case Succeed(c) =>
require {
case Succeed(`c`) => false
case Fail(`c`) => false
case Command(`c`) => true
}
case Fail(c) =>
require {
case Succeed(`c`) => false
case Fail(`c`) => false
case Command(`c`) => true
}
}
}
property("The first command should succeed") {
/* Add a property definition here which requires that the first command does not fail.
* It should yield OK with the events listed in the main method.
*/
// This is what I came up with
require{
case Command(c) =>
require{
case Succeed(`c`)=> true
case Fail(`c`) => false
}
}
}
}
object Checker {
def main(args: Array[String]) {
val events = List(
Command("take_picture"),
Command("get_position"),
Succeed("take_picture"),
Fail("take_picture")
)
val monitor = new EventMonitor
monitor.check(events)
// Desired output should be "true false true"
}
}
【问题讨论】:
-
require()应该返回Boolean但您的代码尝试返回Option[T]。正在测试(匹配)哪些可能是T类型的? -
@jwvh 我扩展了代码:我认为目标是检查事件是否满足属性。以上所有属性都失败了,而不是获得所需的输出。
-
val func: () => Boolean表示func是一个不接受输入并返回Boolean的函数。如果没有输入,它应该如何选择输出,true 或 false? -
formula: => Boolean表示formula是 true 或 false 但确定/评估稍后完成(“call by name”) .我不认为那是你想要的。
标签: scala partialfunction