我一直在尝试学习函数式编程,但我仍然很难像函数式程序员一样思考。其中一个难题是如何实现强烈依赖于循环/执行顺序的索引密集型操作。
例如,考虑以下 Java 代码:
public class Main {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7,8,9);
System.out.println("Nums:\t"+ nums);
System.out.println("Prefix:\t"+prefixList(nums));
}
private static List<Integer> prefixList(List<Integer> nums){
List<Integer> prefix = new ArrayList<>(nums);
for(int i = 1; i < prefix.size(); ++i)
prefix.set(i, prefix.get(i) + prefix.get(i-1));
return prefix;
}
}
/*
System.out:
Nums: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Prefix: [1, 3, 6, 10, 15, 21, 28, 36, 45]
*/
Run Code Online (Sandbox Code Playgroud)
这里,在prefixList函数中,首先克隆 nums 列表,然后对其执行迭代操作,其中索引 i 上的值依赖于索引 i-1 (即需要执行顺序)。然后返回这个值。 …
我正在使用函数式编程风格来解决 Leetcode 的简单问题,计算一致字符串的数量。这个问题的前提很简单:计算谓词“所有值都在另一个集合中”成立的值的数量。
我有两种方法,一种我相当确定其行为符合我的要求,另一种我不太确定。两者都会产生正确的输出,但理想情况下,它们会在输出处于最终状态后停止评估其他元素。
public int countConsistentStrings(String allowed, String[] words) {
final Set<Character> set = allowed.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.toCollection(HashSet::new));
return (int)Arrays.stream(words)
.filter(word ->
word.chars()
.allMatch(c -> set.contains((char)c))
)
.count();
}
Run Code Online (Sandbox Code Playgroud)
在此解决方案中,据我所知,allMatch 语句将在谓词不成立的 c 的第一个实例处终止并计算为 false,从而跳过该流中的其他值。
public int countConsistentStrings(String allowed, String[] words) {
Set<Character> set = allowed.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.toCollection(HashSet::new));
return (int)Arrays.stream(words)
.filter(word ->
word.chars()
.mapToObj(c -> set.contains((char)c))
.reduce((a,b) -> a&&b)
.orElse(false)
)
.count();
}
Run Code Online (Sandbox Code Playgroud)
在此解决方案中,使用相同的逻辑,但allMatch我使用的map是 and then ,而不是reduce。从逻辑上讲,在单个false值来自 …
我找到了关于如何为 C++、Java、Kotlin、Python 等实现不相交集(并集查找算法实现)的文章。它的实现并不是特别困难,尽管存在一些出错的空间。令我惊讶的是,没有任何语言在其标准库中包含这种形式。
是否有一个原因?考虑到大多数标准库中已经存在多少种不同的数据结构,令我惊讶的是没有一个(我发现)包含这一点。是不是太晦涩难懂了?