【发布时间】:2018-07-26 01:15:15
【问题描述】:
我对纯函数的理解是函数的输出只取决于输入。而且它们在引用上是透明的。
但是在我们的代码中会出现副作用。下面是一个例子
import scala.concurrent.Future
case class Customer(fName: String, lName: String)
case class Order(orderId: Int, item: String, quantity: Int)
case class Shipment(shipmentId: Int, orderId: Int, address: String)
trait CustomerRepo {
def findCustomer(userId: String): Future[Customer] = ???
def findLastOrder(customer: Customer): Future[Order] = ???
def findShipment(orderId: Int): Future[Shipment] = ???
}
class ShoppingApp(customerRepo: CustomerRepo) {
def getLastShipment(userId: String): Future[Shipment] = {
for {
customer <- customerRepo.findCustomer(userId)
lastOrder <- customerRepo.findLastOrder(customer)
shipment <- customerRepo.findShipment(lastOrder.orderId)
} yield shipment
}
}
上面是一个基本的例子,我们做了多个副作用(调用数据库)。
getLastShipment 返回一个 Future。这样做是不是一个纯函数。
如果 getLastShipment 不是纯的,那么如何使它成为纯???
【问题讨论】:
-
getLastShipment没有任何不纯的地方。唯一的“问题”是您正在使用Future,它被热切地评估并破坏了RT。除此之外,你很好。 -
期货与整个纯粹的事物背道而驰。除此之外,我认为纯
getLastShipment函数不应该依赖于上下文,这意味着它应该明确要求CustomerRepo作为函数参数。
标签: scala functional-programming purely-functional