Card function in your pocket

I am trying to write a mapfunction as curried and flipped. (First conversion function, then collection). I wrote a function and the compiler accepted it. But I can’t call it. The compiler gives a lack of mapfunc with the arguments supplied. Anyway, here is what I wrote:

func map <A: CollectionType, B> (f: (A.Generator.Element) -> B) -> A -> [B] {
    return { map($0, f) }
}

And this is the test code:

func square(a: Int) -> Int {
    return a * a
}

map(square)

Note. The code is written inside the playground with Xcode 6.3 beta 2

+4
source share
1 answer

The problem is that it is mapnot blocked enough - which collection A? You cannot write a generic function that generates a generic function β€” when you call it, the types of all placeholders must be fully defined.

, map, , A B:

// fixes A to be an Array of Ints, and B to be an Int
let squarer: [Int]->[Int] = map(square)

squarer([1,2,3])  // returns [1,4,9]

// fixes A to be a Slice of UInts, and B to be a Double
let halver: Slice<UInt>->[Double] = map { Double($0)/2.0 }

halver([1,2,3])   // returns [0.5, 1, 1.5]
+2

All Articles