2013-10-16 3 views
1

프로그래밍 언어의 형식 및 다형성에 대해 paper을 읽으면 스칼라에서 형식 멤버에 비슷한 범용 수량화를 표현할 수 있다는 것이 궁금했습니다. 종이에서 예 : 일반적인 신원 함수에 대한 유형과 종이 언어 재미에 다음과 같은 예이다제네릭 함수 유형의 범용 부량

type GenericID = ∀A.A ↦ A 

정확했다 :

value inst = fun(f: ∀a.a ↦ a) (f[Int], f[Bool]) 
value intId = fst(inst(id)) // return a function Int ↦ Int 

가 비슷한 일을 표현 할 수있는 방법이 있나요 스칼라에서?

∀A.A ↦ A는 일반적인 함수의 유형입니다 때 유형 작업의 원인이 입력 생성자 type GenericId[A] = A => A과 동일하지 않습니다

+0

시도 :'유형 세대 [+ _ = _ => _' –

답변

0

시도 : type Gen[+_] = _ => _

scala> def f(x:List[Int]):Gen[List[Int]] = x.reverse 
f: (x: List[Int])Gen[List[Int]] 

scala> f(List(3,4)) 
res0: Function1[_, Any] = List(4, 3) 

scala> def f(x:List[Number]):Gen[List[Number]] = x.reverse 
f: (x: List[Number])Gen[List[Number]] 

scala> f(List(3,4)) 
res1: Function1[_, Any] = List(4, 3) 
+2

나는 당신의 예를 매우는에 보이는 않는 생각하지 않습니다. 'Gen [+ _] = _ => _의 모든 _ 인스턴스는 별도로 정량화됩니다. 실수 형 매개 변수 인 'A'를 사용하면 공분산 주석을 제거하지 않으면 컴파일되지 않는다는 것을 알 수 있습니다. –

1

위 내 댓글에 이어 :

scala> type Gen[+_] = _ => _ 
defined type alias Gen 

scala> def f(x: List[Int]): Gen[List[Int]] = x map (y => s"{$y!$y}") 
f: (x: List[Int])Gen[List[Int]] 

scala> f(List(1, 4, 9)) 
res0: Function1[_, Any] = List({1!1}, {4!4}, {9!9}) 

즉, 유형 식별은에 의해 보존되지 않았습니다.3210.

부록

scala> type Identity[A] = A => A 
defined type alias Identity 

scala> def f(x: List[Int]): Identity[List[Int]] = x => x.reverse 
f: (x: List[Int])List[Int] => List[Int] 

scala> f(List(1, 4, 9)) 
res1: List[Int] => List[Int] = <function1> 

scala> def g(x: List[Int]): Identity[List[Int]] = x => x map (y => s"{$y!$y}") 
<console>:35: error: type mismatch; 
found : List[String] 
required: List[Int] 
     def g(x: List[Int]): Identity[List[Int]] = x => x map (y => s"{$y!$y}") 
관련 문제