I was studying a functor and monad. So I got to know that a functor uses map
and a monad uses flatMap
, and also that definition of map
and flatMap
looks like below.
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> {
// ...
}
}
I totally got those are using different f
parameter(Thanks for this article).
Then, I just wanted to check definition of map
and flatMap
in Optional
, Result
and Array
. Because I heard those are monad as well. In Optional
and Result
, the definition looks like same as custom map
and flatMap
above.
But in Array
, does not.
func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence
I'm bit confused now. Because I knew a monad apply a function that returns wrapped value to wrapped value, so I expected the definition of flatMap
looking like below(definitely wrong).
func flatMap<T>(_ transform: (Element) throws -> [T]) rethrows -> [T]
But It's not anyway.
Am I missing something? Where is the point that I misunderstood?
question from:
https://stackoverflow.com/questions/65950112/definition-of-flatmap-in-swift 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…