use*_*001 6 java haskell functional-programming scala kotlin
我有一组用于验证的函数(规则),它将上下文作为参数,并返回"Okay"或带有消息的"Error".基本上这些可以返回Maybe(Haskell)/ Optional(Java)类型.
在下面我想验证一个Fruit(上下文)的属性,如果验证失败则返回错误消息,否则"Okay"/ Nothing.
注意:我更喜欢纯函数式和无状态/不可变的解决方案.实际上它有点像卡塔.
对于我的实验,我使用了Kotlin,但核心问题也适用于任何支持更高阶函数的语言(例如Java和Haskell).您可以在此处找到指向完整源代码的链接,也可以在最底部找到相同的链接.
鉴于具有颜色和重量的Fruit类,加上一些示例规则:
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")
Run Code Online (Sandbox Code Playgroud)
现在我想使用对相应函数的引用来链接规则评估,而不使用a将上下文指定为参数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"))
}
Run Code Online (Sandbox Code Playgroud)
我不在乎它失败的地方,只关心结果.此外,当函数返回错误时,不应处理其他函数.再说一遍,这听起来像OptionalMonad.
现在的问题是,不知何故,我必须携带fruit上下文check来check调用.
一种解决方法我试过是实现一个Result类,它需要一个上下文值,并有两个子类RuleError(context:Fruit, message:String)和Okay(context).不同的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)
}
Run Code Online (Sandbox Code Playgroud)
我认为,这看起来像一个独异/单子,用return在构造起重Fruit成Result和or作为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")
Run Code Online (Sandbox Code Playgroud)
它允许按预期链接检查:
fun checkRules(fruit:Fruit) {
val res = Result.Okay(fruit).check(::theFruitIsRed).check(::theFruitIsNotTooHeavy)
if (res.isError()) println((res as Result.RuleError).message)
}
Run Code Online (Sandbox Code Playgroud)
//打印:水果不红太重了
然而,这有一个主要缺点:现在Fruit上下文成为验证结果的一部分,尽管在那里并不是绝对必要的.
所以要把它包起来:我正在寻找一种方法
fruit在调用函数时传递上下文哪些函数式编程模式可以解决这个问题?莫纳德是我的直觉,试图告诉我吗?
我更喜欢可以在Kotlin或Java 8中完成的解决方案(用于奖励积分),但其他语言(例如Scala或Haskell)的答案也可能有所帮助.(这是关于概念,而不是语言:))
你可以在这个小提琴中找到这个问题的完整源代码.
Optional您可以使用/创建/类型的幺半群包装器,Maybe例如First在 Haskell 中,它通过返回第一个非 Nothing 值来组合值。
我不知道 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
]
Run Code Online (Sandbox Code Playgroud)
请注意,我在这里利用了Monoid函数实例:
Monoid b => Monoid (a -> b)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
494 次 |
| 最近记录: |