通用函数类型的通用量化 [英] Universal quantification in generic function type

查看:137
本文介绍了通用函数类型的通用量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读有关编程语言中的类型和多态性的纸张时,我想知道是否有可能用Scala在类型成员上表达相似的通用量化.本文中的示例:

Reading the paper on Types and Polymorphism in programming languages, i wondered is it possible to express the similar universal quantification on type members with Scala. Example from the paper:

type GenericID = ∀A.A ↦ A

这是一种通用身份功能,下面的书面语言示例 Fun 是正确的:

Which is a type for generic identity function and the following example in their paper language Fun was correct:

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

在Scala中有某种表达类似的东西的方法吗?

Is there some way to express the similar thing in Scala?

这与类型构造器type GenericId[A] = A => A不同,因为当∀A.A ↦ A是泛型函数的类型时,它是类型操作

This is not the same as type constructor type GenericId[A] = A => A, cause it's a type operation when ∀A.A ↦ A is a type for generic function

推荐答案

以下是我上面的评论:

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})

换句话说,Gen[+_] = _ => _尚未保留类型的标识.

In other words, identity of types has not been preserved by Gen[+_] = _ => _.

附录

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}")

这篇关于通用函数类型的通用量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆