【发布时间】:2021-05-03 02:46:19
【问题描述】:
我正在研究 functor 和 monad。所以我知道了一个仿函数使用map,一个monad使用flatMap,还有map和flatMap的定义如下所示。
enum Box<T> {
case some(T)
case empty
}
extension Box {
func map<U>(_ f: @escaping (T) -> U) -> Box<U> {
// ...
}
}
extension Box {
func flatMap<U>(_ f: (T) -> Box<U>) -> Box<U> {
// ...
}
}
我完全明白那些使用不同的f 参数(感谢this article)。
然后,我只想检查Optional、Result 和Array 中map 和flatMap 的定义。因为我听说那些也是单子。在Optional 和Result 中,定义看起来与上面的自定义map 和flatMap 相同。
但在Array,没有。
func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence
我现在有点困惑。因为我知道 monad 应用了一个将包装值返回到包装值的函数,所以我希望 flatMap 的定义如下所示(绝对错误)。
func flatMap<T>(_ transform: (Element) throws -> [T]) rethrows -> [T]
但无论如何都不是。
我错过了什么吗?我误解的重点在哪里?
【问题讨论】:
标签: swift monads functor flatmap