gpt4 book ai didi

java - 函数式编程 : How to carry on the context for a chain of validation rules

转载 作者:IT老高 更新时间:2023-10-28 13:44:07 24 4
gpt4 key购买 nike

我有一组用于验证的函数(规则),它们以上下文作为参数并返回“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,构造函数中的 returnFruit 提升为 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 上下文
  • 这样我就可以使用相同的方法连续链接(基本上:撰写)多个检查
  • 连同规则函数的结果不改变这些的接口(interface)
  • 无副作用

什么函数式编程模式可以解决这个问题?是我的直觉试图告诉我的 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
]

Ideone Demo

请注意,我在这里利用了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com