I don't think the current situation is all that bad, but I'll play. :)
On Nov 14, 2007 11:21 PM, Andrew Foggin <
andy@...> wrote:
> // won't compile
> //val f4 : ((=> Int, => Int)) => Int = t => { val (a, b) = t; a + b }
> //val pair2 : (=> Int, => Int) = (2, 2)
This can get closer if the types are more explicit:
def f4b(x:Tuple2[Function0[Int],Function0[Int]]):Int={val (a,b)=x; a()*b()}
val f4c:((Tuple2[Function0[Int],Function0[Int]])=>Int) = x => {val
(a,b)=x; a()*b()}
val f4d: ((()=>Int,()=>Int))=>Int = x => {val (a,b)=x; a()*b()}
def toTwo()=2
f4c(toTwo,toTwo) // =4
f4c((toTwo,toTwo)) //=4
val pair3:(()=>Int,()=>Int)=(toTwo,toTwo)
p4c(pair3) //=4
// f4c((2,2)) // found : Int(2) required: () => Int
// if we add this implicit, more things work
implicit def delay[T](t:T)=new Function0[T]{def apply()=t}
f4c(2,2) //=4
f4c((2,2)) //=4
val pair2 : (()=> Int,() => Int) = (2,2)
f4c(pair2) //=4
val pair =(2,2)
// f4c(pair) // found : (Int, Int), required: (() => Int, () => Int)
So, if the function takes tuples, fixed length parameters work.
Unfortunately, requiring tuples is awkward, nonstandard and
inefficent---- unmashalling tuples into parameter lists is the more
interesting direction.
Implicit untupling doesn't work transparently:
val add:(Int,Int)=>Int = _+_;
add(2,3) //5
implicit def Untuple[A,B,C](f:Function2[A,B,C])=new Function1[Tuple2[A,B],C] {
def apply(x:Tuple2[A,B]):C={val (a:A,b:B)=x;f(a,b)}}
// type pattern is unchecked since it is eliminated by erasure
add apply ((2,3)) //5, conversion works here
// but not here:
// add ((2,3)) // wrong number of arguments
It's not to hard to wrap functions by hand:
case class F2[A,B,C](f:Function2[A,B,C]) extends Function2[A,B,C] with
Function1[Tuple2[A,B],C] {
def apply(a:A,b:B)=f(a,b);
def apply(t:Tuple2[A,B])={val (a:A,b:B)=t;f(a,b)}} // still unchecked
val add2=F2(add)
val mul2=F2[Int,Int,Int](_*_)
mul2((3,4))
mul2(6,7) //42
Other cases could be written for other Function lengths and an
overloaded method could construct them all;
I don't see how to extend that from functions to methods.
> So _if_ it was possible to add a more general CBN type '=> T' and allow
> a repeated final element to a Tuple type '(... , T*)' then _perhaps_ a
> function type could be more simply defined as A => B.
A function where all the elements are the same type is an unusually simple case.
-Henry