

Scala 3 幻影类型
source link: https://blog.oyanglul.us/scala/dotty/phantomtype
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Scala 3 幻影类型
可以跑的源码在这里 👉 https://github.com/jcouyang/meow
Phantom Types 指并不是数据类型必要的类型. 其实在 GADT 的例子中已经见过了.
比如 List[Int]
说明构造 List
只需要知道 Int
.
但如果把类型定义成 List[Int, B]
, 那么 B
就是 phantom type, 因为你在构造 List(1)
其实并不需要 B
类型的值.
但是这个可以随意加的额外的类型格外有用, 比如我们可以用 phantom types 来定义类型安全的 Vector
:
enum Nat { case Zero case Succ[A]() extends Nat } import Nat._ type Nat2 = Succ[Succ[Zero.type]] type Nat3 = Succ[Succ[Succ[Zero.type]]] enum Vector[+N <: Nat, +A] { case Cons(head: A, tail: Vector[N, A]) extends Vector[Succ[N], A] case Nil extends Vector[Zero.type, Nothing] } import Vector._ val vector2: Vector[Nat2, Int] = Cons(1, Cons(2, Nil)) val vector3: Vector[Nat3, Int] = Cons(1, Cons(2, Cons(3, Nil)))
长度本身是运行时的值,但是通过phantom types我们把长度弄到了类型上, 这样编译器就能帮忙检查比如, head是不是安全:
def typeSafeHead[A](vec: Vector[Succ[Nat], A]):A = vec match case Cons(head, _) => head
所以如果你想要拿 Nil 的 head, 编译时就会挂:
typeSafeHead(Nil)
Found: (Main.Vector.Nil : Main.Vector[(Main.Nat.Zero : Main.Nat), Nothing]) Required: Main.Vector[Main.Nat.Succ[Main.Nat], Any]
不信? 可以自己在 scastie 上试试: https://scastie.scala-lang.org/jcouyang/JTX3OFXrTCOuq6LNfgRj8Q/8
Recommend
-
44
绝对值、值友专享:HUAWEI 华为 荣耀 Note10 智能手机 6GB+64GB 幻影蓝 2599元包邮(2699元,下单返100元E卡),来自什么值得买甄选出的华为商城优惠产品,汇聚数十万什么值得买网友对该网购产品的点评。
-
45
有问题,上知乎。知乎是中文互联网知名知识分享平台,以「知识连接一切」为愿景,致力于构建一个人人都可以便捷接入的知识分享网络,让人们便捷地与世界分享知识、经验和见解,发现更大的世界。
-
3
事务中的脏读,不可重复读,幻影读:Isolation of databases薛定谔的喵一个人NB的不是标签
-
16
作者: 刘芮/陈帅 编辑:董指导/戴老板 出品:远川研究所科技组 支持:申万宏...
-
17
李昂,腾讯高级开发工程师,主要关注容器存储和镜像存储相关领域,目前主要负责腾讯容器镜像服务和镜像存储加速系统的研发和设计工作。 李志宇,腾讯云后台开发工程师。负责腾讯云 TKE 集群节点和运行时相关的工作,包括 containerd、doc...
-
8
ROG 玩家国度,又名败家之眼,这名字在 PC 玩家间,可以说是无人不知无人不晓。不过随着手游越来越火,尤其是 2018 年暴雪嘉年华上,动视暴雪 CEO 的那句「难道你们都没有手机吗?」,让传统 PC 厂商也坐不住了。 在这一契机之下,ROG 在 2018 年也开始...
-
11
DeFi 代币发行的数十倍回报只是幻影,mStable竞价失败后的反思 ...
-
8
Search 大家正在看 [zz]浏览器urlencode策略差异导致XSS风险 - 16,872 viewspapers更新 - 16,904 views
-
12
哪些三号位可以针对幻影长矛手,除了沙王,军团,想不出啥特别克制的了?19 个回答目前冠绝1246
-
7
雷蛇发布幻影战狼V2幻彩版手柄, 提供6个自定义设置按键及''灵敏扳机''模式
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK