Swit中的功能性编程以分配阵列元素以校正“桶". [英] Functional Programming in Swit to distribute array elements to correct "buckets"

查看:74
本文介绍了Swit中的功能性编程以分配阵列元素以校正“桶".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是函数编程的新手.我的问题是我有一个主数组和一个固定数量的目标"数组.我想根据每个元素的某个值将主数组中的元素分配到正确的结果数组中.

I'm new to functional programming. My problem is that I have a main array and a fixed number of "destination" arrays. I would like to distribute the elements from the main array into the correct resulting array based on a certain value of each element.

我猜测一种方法是让一个映射函数遍历主数组元素,确定正确的目标数组"值(基于某种逻辑),然后将元素添加到该数组中.但是,我不确定这是否是FP.毕竟,这会导致更改要映射的主数组外部的数组的副作用.

I'm guessing that one approach would be to have one map function that goes through the main array elements, determines the correct "destination array" value (based on some logic) and then adds the elements to that array. However, I'm not sure this is very FP. After all, I'm causing a side-effect of changing arrays that are external to the main array that I'm mapping through.

您如何在FP中正确执行此操作?

How would you do this correctly in FP?

推荐答案

这是我的主意:您可以使用reduce消除副作用.与其先创建数组,不如创建一个数组字典.

Here's my idea: you can use reduce to eliminate side effects. Instead of creating the arrays before hand, create a dictionary of arrays.

例如,下面是一个扩展,允许您通过对原始数组的元素应用函数来对其进行分组:

For example, below is an extension that allows you to group elements of the original array by applying a function through them:

extension Array {
    func groupBy<T: Hashable>(f: Element -> T) -> [T: [Element]] {
        return self.reduce([T: [Element]]()) { (var aggregate, element) in
            let key = f(element)

            if aggregate[key] != nil {
                aggregate[key]!.append(element)
            } else {
                aggregate[key] = [element]
            }
            return aggregate
        }
    }
}

示例1:按奇/偶数分组数字

Example 1: group numbers by odd/even

let x = [1,2,3,4]
let y = x.groupBy {
    $0 % 2 == 0 ? "even" : "odd"
}

示例2:按长度分组字符串

Example 2: group strings by length

let arr1 = ["lorem", "ipsum", "dolor", "sit", "amet"]
let arr2 = arr1.groupBy {
    $0.characters.count
}

这篇关于Swit中的功能性编程以分配阵列元素以校正“桶".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆