haskell - How to get generic (polymorphic) lambda in scala? -


just simple example scala:

scala> def f(x: int) = x f: (x: int)int  scala> (f _)(5) res0: int = 5 

let's make generic:

scala> def f[t](x: t) = x f: [t](x: t)t  scala> (f _)(5) <console>:9: error: type mismatch;  found   : int(5)  required: nothing               (f _)(5)                     ^ 

let's @ eta-expansion of polymorphic method in scala:

scala> f _  res2: nothing => nothing = <function1> 

comparison haskell:

prelude> let f x = x  prelude> f 5 5 prelude> f "a" "a" prelude> :t f f :: t -> t 

haskell did infer correct type [t] => [t] here.

more realistic example?

scala> identity _ res2: nothing => nothing = <function1> 

even more realistic:

scala> def f[t](l: list[t]) = l.head f: [t](l: list[t])t  scala> f _ res3: list[nothing] => nothing = <function1> 

you can't make alias identity - have write own function. things [t,u](t: t, u: u) => t -> u (make tuple) impossible use values. more general - if want pass lambda rely on generic type (e.g. uses generic function, example: creates lists, tuples, modify them in way) - can't that.

so, how solve problem? workaround, solution or reasoning?

p.s. i've used term polymorphic lambda (instead of function) function named lambda

only methods can generic on jvm/scala, not values. can make anonymous instance implements interface (and duplicate every type-arity want work with):

trait ~>[a[_], b[_]] { //exists in scalaz   def apply[t](a: a[t]): b[t] }  val f = new (list ~> id) {   def apply[t](a: list[t]) = a.head } 

or use shapeless' poly, supports more complicated type-cases. yeah, it's limitation , requires working around.


Comments