加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala中的类型孔?

发布时间:2020-12-16 18:01:21 所属栏目:安全 来源:网络整理
导读:Haskell提供 typed holes. 例: f :: Int - String - Boolf x y = if (x 10) then True else (g y)g :: String - Boolg s = _ 汇编: Prelude :l HoleEx.hs[1 of 1] Compiling Main ( HoleEx.hs,interpreted )HoleEx.hs:6:7: Found hole `_' with type: Bool
Haskell提供 typed holes.

例:

f :: Int -> String -> Bool
f x y = if (x > 10) then True else (g y)

g :: String -> Bool
g s = _

汇编:

Prelude> :l HoleEx.hs
[1 of 1] Compiling Main             ( HoleEx.hs,interpreted )

HoleEx.hs:6:7:
    Found hole `_' with type: Bool
    Relevant bindings include
      s :: String (bound at HoleEx.hs:6:3)
      g :: String -> Bool (bound at HoleEx.hs:6:1)
    In the expression: _
    In an equation for `g': g s = _
Failed,modules loaded: none.

在Scala中编程时,我通常使用???作为我的Scala代码中的占位符,我还没写过.

但是,使用打字孔对我来说似乎更强大.请注意,我可以用else替换上面的其他(g y)(g 55),但是我得到一个编译时错误:

Prelude> :l HoleEx.hs
[1 of 1] Compiling Main             ( HoleEx.hs,interpreted )

HoleEx.hs:3:39:
    Couldn't match type `Int' with `[Char]'
    Expected type: String
      Actual type: Int
    In the first argument of `g',namely `x'
    In the expression: (g x)
Failed,modules loaded: none.

虽然我可以使用???在Scala中获取占位符实现进行编译,与孔不同,我将使用???获取运行时错误.

scala> def g(x: Int): Int = ???
g: (x: Int)Int

scala> g(5)
scala.NotImplementedError: an implementation is missing

Scala是否有打孔?

解决方法

斯卡拉的???只是抛出异常的简写,相当于Haskell的未定义或只是错误“未实现”或类似.

但是,据我所知,Scala编译器不支持打字孔.但是你可以使用???并检查IDE或Emacs Ensime中的类型以查看其推断类型.

另请注意,与Haskell的Hindley-Milner类型系统的完整类型推断相比,Scala的类型推断是非常小的,因此在Scala编译器中使用类似的类型的东西甚至不会太有意义,直到Martin Odersky和维护者决定Scala需要升级类型推断,我认为不太可能很快发生(但Typelevel人群可能会做一些烹饪).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读