【发布时间】:2015-11-15 18:16:04
【问题描述】:
我确信下面的下划线是单位,意思是函数返回值被忽略。 (以下内容摘自功能和反应域建模一书)。如果这是正确的,那么我对以下代码有疑问:
case class AccountRepository(no: String)
trait AccountService[Account, Amount, Balance] {
def open(no: String, name: String, openingDate: Option[Date]): AccountRepository => Try[Account]
def close(no: String, closeDate: Option[Date])AccountRepository => Try[Account]
def debit(no: String, amount: Amount): AccountRepository => Try[Account]
def credit(no: String, amount: Amount): AccountRepository => Try[Account]
def balance(no: String): AccountRepository => Try[Balance]
}
object App extends AccountService {
def op(no: String) = for {
_ <- credit(no, BigDecimal(100)) // isn't underscore here mean we neglect the return value as its in most cases unit? this mixes me up. How do we refer again to the return value if it goes into the underscore which is normally used for unit response.
_ <- credit(no, BigDecimal(300))
_ <- debit(no, BigDecimal(160))
b <- balance(no)
} yield b
}
scala> op("a-123")
res0: AccountRepository => scala.util.Try[Balance] = <function1>
这段代码能正常工作吗?它会的,只要我们给一些 Function1 的额外功能,这是线程化的类型 通过理解。
所以我应该将存储库传递给 res0 - 我不知道存储库是如何被限制为上述每个贷记/借记方法的?我知道操作从存储库返回一个函数到帐户但是让我感到困惑的是所有这些下划线 - 下划线是否意味着我们摆脱了函数返回值?如果我们忽略返回值,那么我们如何将这些函数传递到存储库?
【问题讨论】:
-
如果您在另一个步骤中或在产量中不需要理解序列步骤中的值,那么您可以将其分配给基本上表示您不需要的下划线它。如果需要,可以输入
val的名称以将其分配给(如本例中的b),以便稍后引用它 -
但是
creditdebit函数正在返回一个函数AccountRepository => Try[Account]所以在我看来我需要从序列步骤返回值,以便我可以进一步应用它正确accountRepository以便可以进行计算,所以我不明白为什么它说不需要它在我看来就像需要返回值但示例没有填充它。
标签: scala functional-programming monads reader-monad