简体   繁体   English

设置OCaml列表的类型

[英]Set Type of OCaml List

I want to set the type of a list to be ints but I have no idea of how to do this. 我想将列表的类型设置为整数,但是我不知道如何执行此操作。 I can do the following: 我可以执行以下操作:

let listOfInts = [];

But that just makes listOfInts be a list with any type allowed to be put in to it. 但这仅使listOfInts成为具有允许放入其中的任何类型的列表。 How can I force the listOfInts to only be a list of ints? 如何强制listOfInts仅是一个整数列表?

This is for making a dictionary in OCaml which maps a string (key) to an int (value). 这是为了在OCaml中制作字典,该字典将字符串(键)映射为int(值)。 For simplicity, I am just going to have the value be the length of the string. 为简单起见,我只将值设为字符串的长度。 Could someone help me out with this? 有人可以帮我这个忙吗? Thanks in advance. 提前致谢。

明确声明类型。

let (listOfInts : int list) = [];

There is no use in forcing the type through an annotation here: you can use [] at any type but, as soon as you use it to create list of elements of a specific type, it will be instantiated to the right type. 在此处通过注释强制类型没有用:可以在任何类型上使用[] ,但是一旦使用它创建特定类型的元素列表,它将被实例化为正确的类型。

Having annotations is occasionally useful for types of values with mutable state that are neither fully inferred nor generalized (eg ref [] ). 对于没有完全推断也不能广义化的具有可变状态的值类型,注释有时会很有用(例如ref [] )。

I don't see how this relates to you wider question of having a map between strings and ints, as this does not involve lists at all. 我不认为这与您在字符串和整数之间具有映射的更广泛的问题有什么关系,因为这根本不涉及列表。 If you want a mutable map you can use Hasthbl , otherwise Map . 如果您想要一个可变的地图,则可以使用Hasthbl ,否则可以使用Map

module StringMap = Map.Make(String)
let m = StringMap.add "foo" 3 StringMap.empty

( m has type int StringMap.t ) m类型为int StringMap.t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM