SML - Creating dictionary that maps keys to values

ε祈祈猫儿з 提交于 2019-12-07 11:49:33

问题


I need to create a dictionary in sml, but I am having extreme difficulty with an insert function.

    type dict = string -> int option

As an example, here is the empty dictionary:

    val empty : dict = fn key => NONE

Here is my implementation of an insert function:

    fun insert (key,value) d = fn d => fn key => value

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

回答1:


You can reason on the signature of the function:

val insert = fn: (string * int) -> dict -> dict

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.

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.

Here is a literal translation:

fun insert (key, value) d = fn s => if s = key then SOME value
                                    else d s


来源:https://stackoverflow.com/questions/14507516/sml-creating-dictionary-that-maps-keys-to-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!