[swift-evolution] [Proposal] Higher Kinded Types (Monads, Functors, etc.)

Donnacha Oisín Kidney oisin.kidney at gmail.com
Thu Dec 17 12:06:03 CST 2015


While I’d love to see HKTs in Swift in the future, and it’s definitely the feature I’m most excited about, I think I’m -1 on this proposal for Swift 3.

I’m not sure if I’m formally correct here, but here’s my understanding so far: Swift’s current type system is powerful enough to express all of the individual Monads that we’re interested in, but it is not capable of a Monad protocol. (or a functor, or applicative, etc.)

If that’s the case, then I can see only two advantages to HKTs:

Code reuse for monadic functions, such as mapM, sequence, etc.
The ability to reason and code about monads generally, rather than about specific monads.

I think the first advantage is the “getting functions for free” idea. However, I’m not sure how much of an advantage it really is: the minimal complete definition for Monad is map, flatMap, and pure. Is mapM and sequence really such an extra hassle? Don’t get me wrong: not having to define them is obviously preferable. I’m just not sure how preferable.

The second advantage, while it’s something I’m certainly interested in, seems much more difficult to justify as an investment of the Swift team’s time.  As someone who’s been learning Haskell for 6-ish months now, I’m only just beginning to grasp those more abstract concepts, and even then it’s still just fun and interesting, rather than useful. I can’t imagine a lot of Comonadic Costate Coalgebra whatever making it into production code.

I feel like right now Swift can get 80% of the benefits from Monadic code, since we can already write Optional, Gen, Parser, State, Par, etc.

> On 17 Dec 2015, at 16:44, Thorsten Seitz via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Big +1 for HKTs from me!
> 
> -Thorsten 
> 
> Am 17.12.2015 um 13:10 schrieb Will Fancher via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>>:
> 
>>> Optional.map and Array.map do different things, and unifying them seems harmful.
>> 
>> In terms of category theory, they're not different. They are both arrows from a to b in the Functor category. Obviously that's horribly abstract, so I'll put it this way: If you think of these map functions not as operations on Optional and Array, and instead think of them simply as ways to compose an arbitrary data structure, they are in fact doing the same thing. On an implementation level, and on a runtime level, they perform differently. But on a type level, a theoretical level, and a categorical level, they are the same. You merely need to accept that when using this abstraction without knowledge of the concrete type, you have no reason to make any assumptions about how the implementation and runtime will behave. At that point, all you need is to be sure that the Functor being passed in abides by the Functor laws, and that's just a matter of convention.
>> 
>>> First, I consider myself a smart person with a very broad experience with non-functional languages, but reading this makes my mind hurt, a lot:
>>> 
>>>>    typeclass Functor f where
>>>>        fmap :: (a -> b) -> f a -> f b
>>> <snip>
>>>> This makes it possible to build functions which operate not just on Maybe, but on any Functor.
>>>> 
>>>>    fstrlen :: Functor f => f String -> f Int
>>>>    fstrlen fstr = fmap length faster
>>> <snip>
>>>>    protocol Functor {
>>>>        typealias A
>>>>        func fmap<FB where FB ~= Self>(f: A -> FB.A) -> FB
>>>>    }
>>> 
>>> I understand what's going on here, but I never, ever want to see this code anywhere near (my) Swift.
>> 
>> HKTs that come from category theory tend to have this effect. They are hard to understand by reading the protocol definition. Admittedly, this is a big flaw with Monads and with Haskell. It takes a reasonable understanding of category theory for the purpose of this code to be obvious to the reader.
>> 
>> (I will point out that in those code examples, I used absolutely abysmal naming conventions. It could be made marginally more readable and understandable if the naming were better)
>> 
>> I'll take this time to make the point that just because you don't like the way the Functor protocol looks, doesn't mean Array and Optional aren't both Functors and Monads. As a matter of mathematics, if the Monad functions can exist on a type, and they would follow the Monad laws, that type is a Monad whether the implementor likes it or not. Of course it still needs manual implementing, but regardless, the type is theoretically a Monad. (This realization is the reason that the Java team decided to implement flatMap for Java 8's Optional class.)
>> 
>>> I believe the way to convince the rest of us (and I would love to be convinced) is to provide a few real, “end-user” app-level use cases and explain the benefit in plain language. In particular, I don't understand the example by Jens Persson, although it seems like a valuable one.
>> 
>> I can (again) link to just a few of the abstract Monadic functions, all of which are very useful in practical applications.
>> 
>> https://hackage.haskell.org/package/base-4.8.1.0/docs/Control-Monad.html <https://hackage.haskell.org/package/base-4.8.1.0/docs/Control-Monad.html>
>> 
>> But perhaps it would also help to describe the architectural decisions that abiding by Monad imposes.
>> 
>> Being Monadic makes you think about data composition, which cleans up the way you design your code. Going back to the Futures example, I could implement future, and subsequently use it, like this:
>> 
>>     public class Promise<T> {
>>         private var handlers: [T -> ()] = []
>>         private var completed: T? = nil
>>         
>>         public init() {
>>         }
>>         
>>         private func onComplete(handler: T -> ()) {
>>             if let completed = completed {
>>                 handler(completed)
>>             } else {
>>                 handlers.append(handler)
>>             }
>>         }
>>         
>>         public func complete(t: T) {
>>             completed = t
>>             for handler in handlers {
>>                 handler(t)
>>             }
>>             handlers = []
>>         }
>>         
>>         public var future: Future<T> {
>>             return Future(promise: self)
>>         }
>>     }
>> 
>>     public struct Future<T> {
>>         private let promise: Promise<T>
>>         
>>         private init(promise: Promise<T>) {
>>             self.promise = promise
>>         }
>>         
>>         public func onComplete(handler: T -> ()) {
>>             promise.onComplete(handler)
>>         }
>>     }
>> 
>>     public func useFutures() {
>>         downloadURLInFuture().onComplete { content in
>>             processContentAsync(content).onComplete { processed in
>>                 processed.calculateSomethingAsync().onComplete {
>>                     ...
>>                         ...
>>                             print(finalProduct)
>>                         ...
>>                     ...
>>                 }
>>             }
>>         }
>>     }
>> 
>> You can see how this resembles the infamous Node.js issue of callback hell, and how the nesting could quickly get out of hand. If only we had some form of composition... Arrows between Futures... Luckily, Future is a Monad (whether I like it or not!)
>> 
>>     // Monad
>> 
>>     public extension Future {
>>         public static func point<T>(t: T) -> Future<T> {
>>             let promise = Promise<T>()
>>             promise.complete(t)
>>             return promise.future
>>         }
>>         
>>         public func flatMap<U>(f: T -> Future<U>) -> Future<U> {
>>             let uPromise = Promise<U>()
>>             
>>             onComplete { t in
>>                 f(t).onComplete { u in
>>                     uPromise.complete(u)
>>                 }
>>             }
>>             
>>             return uPromise.future
>>         }
>>     }
>> 
>> Not only do I now get map and apply for free, but I also get a great method of composing Futures. The example from above can now be rewritten to be much more well composed.
>> 
>>     public func useFutures() {
>>         downloadURLInFuture()
>>             .flatMap(processContentAsync)
>>             .flatMap { $0.calculateSomethingAsync() }
>>             ...
>>             .onComplete { finalProduct in
>>                 print(finalProduct)
>>             }
>>     }
>> 
>> The important thing here is that thinking about Monads helped me discover a better composition model. Now my code can be more readable and well composed.
>> 
>> And again, I'll mention the enormous world of functions and capabilities that can be gotten for free for the sake of even more well-composed code.
>> 
>>> I don't want a flatMap on optionals (which, I believe, was thankfully removed in Swift 2).
>> 
>> And why on Earth not? The concrete implementation of it on Optional is very simple and easy to understand, and the method is incredibly useful. Personally, I use it all the time (it was not removed). And again, just because you don't like using flatMap doesn't mean Optional isn't a Monad.
>> 
>> Finally, I'd like to point out that it doesn't hurt any end users not familiar with Monads if Array implements a higher kinded Monad protocol. As far as they have to be concerned, Array just has these useful map and flatMap functions. Meanwhile, those of us who wish to abstract over Monads in general can write our abstract code and implement Monad on our various types which mathematically have to be Monads. It's a layer of robustness and improvement that unconcerned end users don't have to bother themselves with.
>> 
>> While I understand that the Swift team doesn't have the resources to implement everything that everyone wants, and that HKTs aren't very high on their list of priorities, it seems unreasonable to me that one could think of HKTs and Monads as somehow detrimental to the language.
>> 
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
>  _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151217/6a6a480a/attachment.html>


More information about the swift-evolution mailing list