- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有一组用于验证的函数(规则),它们以上下文作为参数并返回“Okay”或带有消息的“Error”。基本上这些可以返回一个 Maybe
(Haskell)/Optional
(Java) 类型。
在下文中,我想验证 Fruit
(上下文)的属性,如果验证失败则返回错误消息,否则返回“Okay”/Nothing。
注意:我更喜欢纯功能风格和无状态/不可变的解决方案。实际上,它有点像 Kata。
在我的实验中,我使用了 Kotlin,但核心问题也适用于任何支持高阶函数的语言(例如 Java 和 Haskell)。您可以找到 link to the full source code here和最底层的一样。
给定一个带有颜色和重量的水果类,以及一些示例规则:
data class Fruit(val color:String, val weight:Int)
fun theFruitIsRed(fruit: Fruit) : Optional<String> =
if (fruit.color == "red") Optional.empty() else Optional.of("Fruit not red")
fun fruitNotTooHeavy(fruit: Fruit) : Optional<String> =
if (fruit.weight < 500) Optional.empty() else Optional.of("Too heavy")
现在我想使用对相应函数的引用来链接规则评估,而不是使用FruitRuleProcessor
将上下文指定为参数。当处理规则失败时,它不应评估任何其他规则。
例如:
fun checkRules(fruit:Fruit) {
var res = FruitRuleProcessor(fruit).check(::theFruitIsNotRed).check(::notAnApple).getResult()
if (!res.isEmpty()) println(res.get())
}
def main(args:Array<String) {
// "Fruit not red": The fruit has the wrong color and the weight check is thus skipped
checkRules(Fruit("green","200"))
// Prints "Fruit too heavy": Color is correct, checked weight (too heavy)
checkRules(Fruit("red","1000"))
}
我不在乎它失败的地方,只关心结果。此外,当函数返回错误时,不应处理其他函数。同样,这听起来很像 Optional
Monad。
现在的问题是我必须以某种方式将 fruit
上下文从 check
带到 check
调用。
我尝试的一个解决方案是实现一个 Result
类,该类将上下文作为值并具有两个子类 RuleError(context:Fruit, message:String)
和 好的(上下文)
。 Optional
的不同之处在于,现在我可以环绕 Fruit
上下文(想想 T = Fruit
)
// T: Type of the context. I tried to generify this a bit.
sealed class Result<T>(private val context:T) {
fun isError () = this is RuleError
fun isOkay() = this is Okay
// bind
infix fun check(f: (T) -> Result<T>) : Result<T> {
return if (isError()) this else f(context)
}
class RuleError<T>(context: T, val message: String) : Result<T>(context)
class Okay<T>(context: T) : Result<T>(context)
}
我认为这看起来像一个 monoid/Monad,构造函数中的 return
将 Fruit
提升为 Result
和 或
是绑定(bind)
。虽然我尝试了一些 Scala 和 Haskell,但诚然我对此并不那么有经验。
现在我们可以将规则更改为
fun theFruitIsNotTooHeavy(fruit: Fruit) : Result<Fruit> =
if (fruit.weight < 500) Result.Okay(fruit) else Result.RuleError(fruit, "Too heavy")
fun theFruitIsRed(fruit: Fruit) : Result<Fruit> =
if (fruit.color == "red") Result.Okay(fruit) else Result.RuleError(fruit, "Fruit not red")
允许按预期链接检查:
fun checkRules(fruit:Fruit) {
val res = Result.Okay(fruit).check(::theFruitIsRed).check(::theFruitIsNotTooHeavy)
if (res.isError()) println((res as Result.RuleError).message)
}
//打印:果实不红太重了
但是,这有一个主要缺点:Fruit
上下文现在成为验证结果的一部分,尽管它在其中并不是绝对必要的。
总结一下:我正在寻找方法
fruit
上下文什么函数式编程模式可以解决这个问题?是我的直觉试图告诉我的 Monads 吗?
我更喜欢可以在 Kotlin 或 Java 8 中完成的解决方案(以获得奖励积分),但其他语言(例如 Scala 或 Haskell)的答案也可能会有所帮助。 (这是关于概念,而不是语言:))
您可以在 this fiddle 中找到此问题的完整源代码.
最佳答案
您可以使用/创建 Optional
/Maybe
类型的 monoid 包装器,例如 First
在 Haskell 中,它通过返回第一个非空值来组合值。
我不知道 Kotlin,但在 Haskell 中它看起来像这样:
import Data.Foldable (foldMap)
import Data.Monoid (First(First, getFirst))
data Fruit = Fruit { color :: String, weight :: Int }
theFruitIsRed :: Fruit -> Maybe String
theFruitIsRed (Fruit "red" _) = Nothing
theFruitIsRed _ = Just "Fruit not red"
theFruitIsNotTooHeavy :: Fruit -> Maybe String
theFruitIsNotTooHeavy (Fruit _ w)
| w < 500 = Nothing
| otherwise = Just "Too heavy"
checkRules :: Fruit -> Maybe String
checkRules = getFirst . foldMap (First .)
[ theFruitIsRed
, theFruitIsNotTooHeavy
]
请注意,我在这里利用了 Monoid
函数实例:
Monoid b => Monoid (a -> b)
关于java - 函数式编程 : How to carry on the context for a chain of validation rules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46552329/
为什么下面的工作: from itertools import chain 但下面的不是吗? import itertools.chain as chain 最佳答案 import foo.bar 语
1、逻辑流 在屏幕开发中,存在如下逻辑流: PBO(Process Before Output):屏幕输出之前触发 PAI(Process After Input):用户在屏幕中执
我正在尝试链接一系列任务,返回一个 promise ,在链的最后执行并行执行。下面的代码不起作用,我认为你可以传递任何在“then”内返回 promise 的对象。有没有适当的方法来实现这一点。谢谢。
您能否对 itertools 中的 chain() 和 chain.from_iterable 这两个方法给出更简单的解释? 我搜索了知识库和 python 文档,但我很困惑。 我是 python 新
问题的简短版本 我就是否使用 ./*this 与 ->/this 寻求建议,即 C++ (*this).chained().methods() 与 this->chained()->methods()
itertools 中所有有趣的迭代器让我着迷,但我的一个困惑是这两个函数之间的区别以及为什么存在 chain.from_iterable。 from itertools import chain d
Swift 中的“可选链接”和“可选调用链接”之间有语义差异吗? 最佳答案 我暂时会回答“否”,没有语义差异。 “Optional Chaining”在“Swift 编程语言(Swift 2 Prer
我有一个服务器和一个客户端。我让他们都在同一台机器上运行。我正在尝试在客户端和服务器之间建立 SSL 连接。我已经使用以下 keytool 命令为服务器和客户端生成了证书。 对于客户keytool -
我有一些数据要从带有 lodash 的 json 数组中拒绝。我需要拒绝不需要的多个键值。 我在想我可以链接映射并再次使用 reject 函数,或者可能为 reject 方法编写一个谓词函数以供使用。
我真的什么都试过了。令人惊讶的是,谷歌对此没有太多答案。 当某个 .csv 文件上传到 S3 存储桶时,我想解析它并将数据放入 RDS 数据库。 我的目标是学习 lambda serverless 技
我最近一直在研究区 block 链,并偶然发现了以太坊和 chain.com 这两个平台似乎都有助于开发和部署区 block 链应用程序,其中 chain.com 专门针对金融公司。 尽管如此,两者之
asyncFunction1 .then(asyncFunction2, errorHandlerFunction) .then(Function3, errorHandlerFunc
已结束。此问题正在寻求书籍、工具、软件库等的推荐。它不满足Stack Overflow guidelines 。目前不接受答案。 我们不允许提出寻求书籍、工具、软件库等推荐的问题。您可以编辑问题,以便
我得到 RqlRuntimeError: Expected type TABLE_SLICE but found SELECTION: 链接 getAll 和 between 方法时出现错误。 r.d
我对 jquery ui 很陌生,但由于我的项目的性质,我有点陷入了困境!基本上我需要帮助的是,我有一个文件,该文件将某些自定义设置应用于 jquery ui 可拖动小部件,并且我想进一步自定义以启用
我有一个函数应该一个接一个地运行,例如: function cutTomatoesAlone(Kg){ // slice my stuff } function cookTomatoes(Mi
Android 新手,我想制作一些流畅的动画。 我在设备上有一个包含效果的文件,每个效果都是一个动画。该文件告诉我何时播放效果以及效果持续时间。 问题是我不能动态链接 animatorSet : An
我有一个 Action,叫做 ShowData从数据库中恢复数据并将其放入 jsp。 struts.xml ... foo.jsp ... 在 foo.jsp 页面中,我有一个表单和我使用
我正在尝试使用三元运算符编写类似这样的东西(由于 jsx 语法限制而需要) if(!this.state.msg) { if(this.state.ask.length != 0) {
这段代码有区别吗? var query = DbContext.Customers .Where() .Include("Address
我是一名优秀的程序员,十分优秀!