[swift-evolution] swift generics not generic enough?

Baojun Wang wangbj at gmail.com
Mon Apr 25 18:50:53 CDT 2016


Hi List,


I'm very new to swift, and feel quite excited about the features provided
by swift.


when I tried below example in playground (many of them borrowed from
swiftz), I find some swift generics looks wired (to me)


(1) When use generics in extension, typealias can refer to generics defined
elsewhere

(2) types cannot be inferred types as it supposed to be

(3) No higher minded types, I found some discussion in the old mail thread,
will HKT be part of future swift?



// code snippet (using swift 2.2)


public struct K0 {}

public struct K1<A> {}


public protocol Functor{

    associatedtype A

    associatedtype B

    associatedtype FA = K1<A>

    associatedtype FB = K1<B>


    func fmap(f : A -> B, _ fa : FA) -> FB

}


public enum Maybe<E> {

    case Nothing

    case Just(E)

}


extension Maybe : Functor {

    public typealias A = E         // <---- (1), where is E come from? In
extension Maybe, E isn't part of any context?

    public typealias B = Any

    public typealias FA = Maybe<A>

    public typealias FB = Maybe<B>



    public func fmap<B> (f : A -> B, _ fa: FA) -> Maybe<B> {

        switch(fa) {

        case .Nothing:

            return .Nothing

        case let (.Just(a)):

            return .Just(f(a))

        }

    }

}


public func fmap<A, B> (f : A -> B, _ fa : Maybe<A>) -> Maybe<B> {       //
<----- lack of Higher minded type, thus every extension implements protocol
``Functor`` need this boilerplate?

    return fa.fmap(f, fa)

}


func succ (x : Int) -> Int {

    return 1 + x

}


let x0 = .Nothing          // <------- type error, cannot infer x0

let x1 = .Just(1)          // <------- type error, cannot infer x1, which
is (Maybe Int)

let x2 : Maybe<Int> = .Just(1)

let x3 = fmap(succ, x2)


Thanks
baojun
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160425/5cf6f99a/attachment.html>


More information about the swift-evolution mailing list