swift - 如何在 swift 中编写 not/negate 高阶函数?

标签 swift functional-programming higher-order-functions

我是一名 Javascript 开发者,我喜欢使用 not/negate 函数:

function not (predicateFunc) {
    return function () {
        return !predicateFunc.apply(this, arguments);
    };
}

我正在尝试用 swift 做同样的事情:

func not <A> (_ f: @escaping (_ A: Any) -> Bool) -> (A) -> Bool {
    return { a in !f(a) }
}

但是我遇到了这样的错误

generic parameter 'T' could not be inferred

Cannot convert value of type '(_) -> Bool' to expected argument type '(Any) -> Bool'

我正在寻找的结果是当我有这样的功能时:

func isEmpty<T: Collection>(collection: T) -> Bool {
    return collection.count == 0
}

我可以像这样创建一个 notEmpty 函数:

let notEmpty = not(isEmpty)

然后像这样使用它

   notEmpty([3,4,5]) // true

我做错了什么?

最佳答案

使用 Any 是一种代码味道。您可以直接扩展 Collection:

extension Collection {
    var notEmpty: Bool {
        return !isEmpty
    }
}

[1, 3, 5].notEmpty // true

not 的函数定义可以像这样工作:

func not <A> (_ f: @escaping (_ a: A) -> Bool) -> (A) -> Bool {
    return { a in !f(a) }
}

但是要调用它你需要这样的东西:

let arrayNotEmpty = not { (array: [Int]) in array.isEmpty }
arrayNotEmpty([1, 3, 5]) // true

关于swift - 如何在 swift 中编写 not/negate 高阶函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53975326/

相关文章:

scala - 如何使此代码起作用?

r - R 中的更高级别函数 - 是否有官方的 compose 运算符或 curry 函数?

ios - 可以在 objective c 中使用 swift 中的 array reduce 概念吗?

ios - 在导航 Controller 后退按钮上委托(delegate)/展开 Segue

haskell - 从字典和维度生成所有可能组合的功能性尾递归方式

algorithm - 推广组合函数?

swift - Apple Watch Glance——使用 NSURL 加载数据

json - 使用 swift 4 从服务器加载数据

haskell - 如何使用高阶函数实现这种基于IO的循环?

javascript - 'new Array' 上的 forEach 没有按照我的预期进行