我編寫的練習旨在幫助我理解標準ML中的簽名,結構和函子。我似乎無法得到它的工作。僅供參考,我使用爲什麼我不能訪問我的結構的內部ORD_SET結構?
Standard ML of New Jersey v110.75 [built: Sun Jan 20 21:55:21 2013]
我有一個「對象,你可以計算幅度」以下ML簽名:
signature MAG_OBJ =
sig
type object
val mag : object -> int
end
如果我想給「爲int的結構設置與幅度,」我可能有一個結構的有序INT與標準庫的ORD_SET簽名使用方法如下:
structure OrderedInt : ORD_KEY =
struct
type ord_key = int
val compare = Int.compare
end
然後,我可以創造一個仿函數給我想要的類型和PR的結構operties:
functor MakeMagSet(structure ELT : ORD_KEY) : MAG_OBJ =
struct
structure Set : ORD_SET = RedBlackSetFn(ELT)
type object = Set.set
val mag = Set.numItems
end
到目前爲止好(一切編譯,至少)。現在我爲我的OrderedInt結構創建結構的實例,我上面提出:
structure IntMagSet = MakeMagSet(structure ELT = OrderedInt)
但是當我嘗試使用它(創建一組,並計算其大小),我得到一個錯誤:
val X = IntMagSet.Set.addList(IntMagSet.Set.empty, [0,1,2,3,4,5,6,7,8,9])
給出了錯誤:
Error: unbound structure: Set in path IntMagSet.Set.empty.addList
據我瞭解,歸咎於不透明的簽名使用:>使得它如此一個無法訪問未在簽字:明確定義的任何內部結構e,但是我透明地賦予了MAG_OBJ,所以我應該可以訪問Set結構,對嗎?我在這裏錯過了什麼?
[編輯]
即使重寫特異性結合我想要的結構功能的仿函數是沒有好處:
functor MakeMagSet(structure ELT: ORD_KEY) : MAG_OBJ =
struct
structure Set : ORD_SET = RedBlackSetFn(ELT)
type object = Set.set
val mag = Set.numItems
val empty = Set.empty
val addList = Set.addList
end
嘗試訪問「空」和「addList」給綁定變量的錯誤。
在另一方面,試圖明確定義設置結構的結構之外,並使用其功能提供了在調用MAG類型錯誤:
Error: operator and operand don't agree [tycon mismatch]
operator domain: IntMagSet.object
operand: Set.set
in expression:
IntMagSet.mag X
剛剛意識到我不能說「IntMagSet.Set.empty.addList」,因爲我很傻,太習慣了面向對象的風格。我認爲這裏仍然存在問題,但我必須編輯該問題。 – JeremyKun 2013-04-29 00:24:43