【问题标题】:How to use infix operator from a SML module?如何使用 SML 模块中的中缀运算符?
【发布时间】:2012-12-17 05:14:43
【问题描述】:

我要编写以下代码并且我使用 SML/NJ:

signature STACK=
sig

    type 'a Stack

    val empty :'a Stack
    val isEmpty : 'a Stack -> bool

    val cons : 'a*'a Stack -> 'a Stack
    val head : 'a Stack ->'a
    val tail : 'a Stack -> 'a Stack
    val ++ : 'a Stack * 'a Stack -> 'a Stack
end
structure List : STACK = 
 struct
 infix 9 ++
type 'a Stack = 'a list

val empty = []
fun isEmpty s = null s

fun cons (x,s) = x::s
fun head s = hd s
fun tail s = tl s
fun xs ++ ys = if isEmpty xs then ys else cons(head xs, tail xs ++ ys)    

end

我想使用解释器中的 ++ 运算符,但是当我编写 s1 List.++ s2 其中 s1 和 s2 堆栈类型时,我得到了运算符不是函数的消息。

谢谢。

【问题讨论】:

    标签: smlnj


    【解决方案1】:

    您已将++ 声明为结构内的中缀,并且该声明仅限于结构的范围(在struct...end 内)。您可以在顶层将其声明为中缀,或将其用作前缀,但在 SML 中,中缀声明不是签名的一部分。

    - List.++ ([1], [2,3]);
    val it = [1,2,3] : int Stack
    
    - infix 9 ++;
    infix 9 ++
    - open List;
    ...
    - [1] ++ [2,3];
    val it = [1,2,3] : int Stack
    

    查看一些有趣的技巧:http://www.mlton.org/InfixingOperators

    【讨论】:

    • 即使我把它放在顶层结构之外,当我尝试使用它时,我会收到错误消息,即运算符不是函数。
    • open List 结构了吗?用对我有用的方法编辑了答案。
    • 好的,打开列表时它起作用了。但这意味着我们“污染”了顶级命名空间?
    • 是的,AFAICT 这是 SML 的一个(微小)限制,导致 MLton 网站的该页面中描述的尴尬。
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2021-05-20
    • 2017-01-25
    相关资源
    最近更新 更多