在过去的几个月里,我尝试使用函数式编程范例进行编码。现在我在 OOP 中有一个解决方案,并且我正在尝试找到一个功能性的解决方案。
问题很简单。我有一个算法,它生成两个不同的数组作为结果(a 和 b)。现在,我想检查一下结果有多好。所以我给他们写了几个评价标准。我希望伪java源代码对你来说没问题!
// first the Algorithm class
class Algorithm {
private []a;
private []b;
Algorithm(input) {
computeResult();
}
getA(){return a;}
getB(){return b;}
void computeResult() {
...
... // time-consuming operations
... // set values for a and b
...
}
}
// this class tests the Algorithm using a list of evaluation criteria
class AlgorithmTest {
AlgorithmTest() {
...
... // Definition of input
... // Definition of list of evaluation criteria evals
...
Algorithm algorithm = new Algorithm(input); // Compute the result
for (EvaluationCriterion eval : evals) {
System.out.println(eval.getClassSimpleName()); // Print name of class
System.out.println(eval.evaluate(algorithm)); // Print evaluation result
}
}
main () {
new AlgorithmTest();
}
}
interface EvaluationCriterion {
double evaluate(Algorithm a);
}
// an example implementation of a criterion
class EvaluationA implements EvalutationCriterion{
double evaluation(Algorithm algorithm) {
a = algorithm.getA();
b = algorithm.getB();
double c = anotherComputation(a, b);
return c;
}
double anotherComputation(a, result){
... // compute and return result
}
}
是否可以使用函数式编程范式“转换”此源代码? 我确信如此,但是您仍然可以像 OOP 方法一样轻松添加新的评估标准吗?
我可以编写一个名为算法的模块,其中包含计算 a 或 b 的纯函数。在这种情况下,我必须计算两次,这需要很多时间。
但是如何使用多个评估函数进行评估步骤呢?
最佳答案
But how to do the evaluation step using multiple evaluation functions?
您可以将要使用的函数作为一流值传递。
您的类型 EvaluationCriterion
基本上只是函数类型 Algorithm -> Double
(采用 Haskell 语法)。 EvaluationA
、EvaluationB
等不需要是新类型。它们只是 EvaluationCriterion
类型的值。您可以将它们作为值传递,构建 [EvaluationCriterion]
类型的列表等。
具有讽刺意味的是,您已经在解决方案中使用了一流的函数。这种抽象弱的 OOP 语言缺乏一流的函数,因此您必须应用标准化的解决方法(“设计模式”)。将其转换为函数式语言(或只是合理的 OOP 语言)是消除复杂性的问题。
现在,至于如何消除算法的有状态性
,我还没有考虑过。但请记住,FP 并不意味着“永远没有状态”。缓存纯函数结果是很常见的事情。
关于java - 如何将这个简单的 OOP 程序转换为函数式编程语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3941394/