SML-创建将键映射到值的字典 [英] SML - Creating dictionary that maps keys to values

查看:216
本文介绍了SML-创建将键映射到值的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在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

当提供keyvalue和字典d时,您想找回新的字典d'.由于dictstring -> 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.可能发生两种情况:当skey相同时,您将返回关联的值,否则将通过使用键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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆