查看键是否存在于字符串映射中 [英] See if key exists in a String Map

查看:71
本文介绍了查看键是否存在于字符串映射中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用Map函子创建一个字符串映射:module StringMap = Map.Make(String).

I am currently using the Map functor to create a string map: module StringMap = Map.Make(String).

然后,我尝试将一组字符串映射到'a对象列表插入StringMap中.要检查密钥是否已经存在,我正在执行以下操作:

I then am trying to insert a set of mappings of strings to a list of 'a objects into the StringMap. to check if the key already exists, I am doing the following:

match StringMap.find_opt key my_map with
  | None -> StringMap.add key [child] my_map
  | Some l -> StringMap.add key (child::l) my_map 

但是,当我编译时,我收到一条错误消息,说find_opt的绑定具有未绑定的值,即使它是在签名中定义的:

However, when I compile, I get an error saying the binding for find_opt has an unbound value, even though it is defined in the signature: https://ocaml.org/learn/tutorials/map.html.

我也尝试使用StringMap.mem key my_map,但出现以下错误:

I have also tried using StringMap.mem key my_map, but get the following error:

Error: This expression has type string but an expression was expected of type
     'a StringMap.t =
       (StringMap.Key.t, 'a, StringMap.Key.comparator_witness)
       Base__Map.t

我环顾四周,看看是否有输入错误或其他错误,但一直找不到.关于我为什么会遇到这些错误的任何想法?

I've looked around to see if there is a typing error or something but have been unable to find anything. Any ideas as to why I am getting either of these errors?

推荐答案

根据您正在使用Base(或Core)库的错误消息,它们是OCaml标准库的替代品,并且具有不同的接口.特别是Map界面中的find函数已经返回了选项类型,因此没有find_opt函数.

According to the error message you're using Base (or Core) library, which are substitutions for the OCaml standard library and have the different interface. In particular, the find function in the Map interface already returns an option type, and thus there is no find_opt function.

也许,您已经使用了jbuilder教程中的一些示例,该示例自动启用了该库.

Perhaps, you've used some example from the jbuilder tutorial that enables this library automatically.

您可以切换到标准库,也可以通过打开兼容性模块Caml(例如

You can either switch to the standard library or enable the compatibility with the vanilla OCaml standard library by opening the compatibility module Caml, e.g.,

open Caml

(* your code goes below *)

这篇关于查看键是否存在于字符串映射中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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