Reputation: 17544
please, check my snippet, the question is there (my english is too bad to be able to explain my trouble by the words :))
func flip1<A, B, C>(f : ((A, B) -> C), _ b : B, _ a : A) -> C {
return f(a, b)
}
flip1(-, 2, 1) // -1
flip1(/, 2.0, 3.0) // 1.5
// partialy curried version
func flip2<A, B, C>(f : (A, B) -> C, _ i : B, _ j : A) -> C {
return f(j, i)
}
print(flip2(- , 2, 1)) // -1
print(flip2(/,2.0,3.0)) // 1.5
compiles without trouble, but how to use it???
// full curried version
// compiles without trouble, but how to use it???
func flip3<A, B, C>(f : A -> B -> C) -> B -> A -> C {
return { b in { a in f(a)(b) } }
}
/*
* flip3(/)(2.0)(3.0)
*
* error: ambiguous reference to member '/'
* it meands there are more than one candidate for / function
*/
// we need curried version of /, let's define it
func curry<A,B,C>(f: (A, B) -> C) -> A -> B -> C {
return { a in { b in f(a, b) } }
}
/*
* let divideUnknownType = curry(/)
* compiler still complain, as expected :-)
* error: ambiguous use of operator '/'
*/
// and then define the type of it
let divideDoubles: Double->Double->Double = curry(/)
let divideIntegers: Int->Int->Int = curry(/)
// :-)
print(flip3(divideDoubles)(2.0)(3.0)) // 1.5
print(flip3(divideDoubles)(2)(3)) // 1.5
print(flip3(divideIntegers)(2)(3)) // 1
as you can see, it breaks my 'generic' approach. any idea how to solve it?
Upvotes: 0
Views: 98
Reputation: 2758
func flip3<A, B, C>(f: (A, B) -> C) -> B -> A -> C {
return { b in { a in f(a, b) } }
}
flip3(/)(2.0)(3.0) // 1.5
Upvotes: 1