SML-创建将键映射到值的字典 [英] SML - Creating dictionary that maps keys to values
问题描述
我需要在sml中创建一个字典,但是在插入功能上我遇到了极大的困难.
I need to create a dictionary in sml, but I am having extreme difficulty with an insert function.
type dict = string -> int option
例如,这是空字典:
val empty : dict = fn key => NONE
这是我对插入函数的实现:
Here is my implementation of an insert function:
fun insert (key,value) d = fn d => fn key => value
但是这是错误的类型,我需要的是insert:(string * int)-> dict-> dict. 我搜索了从惰性函数到实现字典的所有内容. 任何帮助或指示将不胜感激!
But this is of the wrong type, what I need is insert : (string*int) -> dict -> dict. I've searched everything from lazy functions to implementing dictionaries. Any help or direction would be greatly appreciateds!
如果您仍然对我要实现的内容感到困惑,那么我起草了我在调用简单查找函数时应该得到的内容
If you are still confused on what I am trying to implement, I drafted up what I should expect to get when calling a simple lookup function
fun lookup k d = d k
- val d = insert ("foo",2) (insert ("bar",3) empty);
val d = fn : string -> int option
- lookup2 "foo" d;
val it = SOME 2 : int option
- lookup2 "bar" d;
val it = SOME 3 : int option
- lookup2 "baz" d;
val it = NONE : int option
推荐答案
您可以对函数的签名进行推理:
You can reason on the signature of the function:
val insert = fn: (string * int) -> dict -> dict
当提供key
,value
和字典d
时,您想找回新的字典d'
.由于dict
是string -> int option
,因此d'
是一个接受string
并返回int option
的函数.
When you supply key
, value
and a dictionary d
, you would like to get back a new dictionary d'
. Since dict
is string -> int option
, d'
is a function takes a string
and returns an int option
.
假设您为该函数提供了字符串s
.可能发生两种情况:当s
与key
相同时,您将返回关联的值,否则将通过使用键s
查找d
来返回值.
Suppose you supply a string s
to that function. There are two cases which could happen: when s
is the same as key
you return the associated value, otherwise you return a value by looking up d
with key s
.
这是一个字面翻译:
fun insert (key, value) d = fn s => if s = key then SOME value
else d s
这篇关于SML-创建将键映射到值的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!