如何在swift中编写not/NEVERISE高阶函数?
我是一名Javascripter,我喜欢使用如何在swift中编写not/NEVERISE高阶函数?,swift,functional-programming,higher-order-functions,Swift,Functional Programming,Higher Order Functions,我是一名Javascripter,我喜欢使用not/negate函数: function not (predicateFunc) { return function () { return !predicateFunc.apply(this, arguments); }; } 我正试图对斯威夫特做同样的事情: func not <A> (_ f: @escaping (_ A: Any) -> Bool) -> (A) -> Boo
not/negate
函数:
function not (predicateFunc) {
return function () {
return !predicateFunc.apply(this, arguments);
};
}
我正试图对斯威夫特做同样的事情:
func not <A> (_ f: @escaping (_ A: Any) -> Bool) -> (A) -> Bool {
return { a in !f(a) }
}
及
我期待的结果是当我有这样一个函数时:
func isEmpty<T: Collection>(collection: T) -> Bool {
return collection.count == 0
}
let notEmpty = not(isEmpty)
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
然后像这样使用它
notEmpty([3,4,5]) // true
我做错了什么?使用
Any
是一种代码气味。您可以直接扩展集合:
extension Collection {
var notEmpty: Bool {
return !isEmpty
}
}
[1, 3, 5].notEmpty // true
not
的函数定义可以如下所示:
func isEmpty<T: Collection>(collection: T) -> Bool {
return collection.count == 0
}
let notEmpty = not(isEmpty)
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
使用
Any
是一种代码气味。您可以直接扩展集合:
extension Collection {
var notEmpty: Bool {
return !isEmpty
}
}
[1, 3, 5].notEmpty // true
not
的函数定义可以如下所示:
func isEmpty<T: Collection>(collection: T) -> Bool {
return collection.count == 0
}
let notEmpty = not(isEmpty)
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
您有两个错误:
- 您正在使用
作为类型参数和参数名称A
- 您正在使用
作为参数类型,而不是使用类型参数(Any
)作为参数类型A
func not<A>(predicate: @escaping (A) -> Bool) -> (A) -> Bool {
return { !predicate($0) }
}
你会得到这个错误:
let notEmpty = not(isEmpty)
^ Generic parameter 'A' could not be inferred
问题是这段代码试图创建一个泛型闭包,但Swift不支持泛型闭包
也就是说,非空的类型是什么?可能是这样的:
<A: Collection>(A) -> Bool
(A)->Bool
Swift不支持这一点。您有两个错误:
- 您正在使用
A
作为类型参数和参数名称
- 您正在使用
Any
作为参数类型,而不是使用类型参数(A
)作为参数类型
试试这个:
func not<A>(predicate: @escaping (A) -> Bool) -> (A) -> Bool {
return { !predicate($0) }
}
你会得到这个错误:
let notEmpty = not(isEmpty)
^ Generic parameter 'A' could not be inferred
问题是这段代码试图创建一个泛型闭包,但Swift不支持泛型闭包
也就是说,非空的类型是什么?可能是这样的:
<A: Collection>(A) -> Bool
(A)->Bool
斯威夫特并不支持这一点。这并不是我想要的。我仍然希望使用泛型集合,而不是数组:[Int]
。难道没有更好的办法吗?不是我想要的。我仍然希望使用泛型集合,而不是数组:[Int]
。难道没有更好的办法吗?很好!但我得到了一个编译器错误:无法推断泛型参数“a”
@AmitErandole显然在声明中,您必须告诉编译器类型为let notEmpty:([Int])->Bool=not(isEmpty)
nice!但我得到了一个编译器错误:无法推断泛型参数“a”
@AmitErandole显然在声明中,您必须告诉编译器类型为let notEmpty:([Int])->Bool=not(isEmpty)