Skip to content

Instantly share code, notes, and snippets.

@Skyb0rg007
Created April 9, 2020 23:26
Show Gist options
  • Save Skyb0rg007/bef9f5e639118b2130e1ce842caccac3 to your computer and use it in GitHub Desktop.
Save Skyb0rg007/bef9f5e639118b2130e1ce842caccac3 to your computer and use it in GitHub Desktop.
signature DICT =
sig
type 'a dict
type key
exception NotFound of key
val empty : 'a dict
val find : key * 'a dict -> 'a (* may raise NotFound *)
val bind : key * 'a * 'a dict -> 'a dict
end
structure StringDict = DictFn(structure Key = StringKey)
val my_dict =
List.foldr (fn ((k, v), d) => StringDict.bind (k, v, d)) StringDict.empty
[ ("foo", 1)
, ("baz", 2)
, ("bax", 3)
, ("bar", 4)
]
fun index k =
print ("my_dict[" ^ k ^ "] = " ^ Int.toString (StringDict.find (k, my_dict)) ^ "\n")
handle StringDict.NotFound k => print ("my_dict[" ^ k ^ "] = NULL\n")
val () = List.app index ["foo", "bar", "asdf"]
functor DictFn (structure Key : KEY) :> DICT where type key = Key.key =
struct
type key = Key.key
type 'a dict = (key * 'a) list
exception NotFound of key
val empty = []
fun find (k, d) =
case List.find (fn (k', _) => Key.equal (k, k')) d
of NONE => raise NotFound k
| SOME (_, v') => v'
fun bind (k, v, d) = (k, v)::d
end
signature KEY =
sig
type key
val equal : key * key -> bool
end
.DEFAULT: dict-test
dict-test: dict-test.uo
mosmlc -toplevel $^ -o $@
key-sig.ui key-sig.uo: key-sig.sml
mosmlc -toplevel -c $^
dict-sig.ui dict-sig.uo: dict-sig.sml
mosmlc -toplevel -c $^
dict.ui dict.uo: key-sig.ui dict-sig.ui dict.sml
mosmlc -toplevel -c $^
string-key.ui string-key.uo: key-sig.ui string-key.sml
mosmlc -toplevel -c $^
dict-test.ui dict-test.uo: string-key.ui dict.ui dict-test.sml
mosmlc -toplevel -c $^
clean:
$(RM) *.ui *.uo test
structure StringKey :> KEY where type key = string =
struct
type key = string
val equal = op =
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment