0

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?

16
  • 1
    For the life of me I cannot see the difference between flip1 and flip2? Commented Apr 3, 2016 at 13:27
  • (/) as (Double, Double) -> Double will help you grab the correct version of /. Commented Apr 3, 2016 at 13:29
  • @milos you are right! :-), just skip it, i need some idea how make flip3 really generic, so flip3(/)(2.0)(3.0) will work .... It is even possible? Commented Apr 3, 2016 at 13:36
  • It should be: func flip3<A, B, C>(f: (A, B) -> C) -> B -> A -> C Commented Apr 3, 2016 at 13:39
  • 2
    @Darko He is not declaring any. (or you're making a general comment of approval?) Commented Apr 3, 2016 at 14:44

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

2 Comments

You are welcome. You've just made a slight error with f parameter, which has to take two arguments (A, B) -> C to match functions like /...
Yes, i see it now. My head is like hot air balloon ... :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.