简体   繁体   中英

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. How can I force the listOfInts to only be a list of ints?

This is for making a dictionary in OCaml which maps a string (key) to an int (value). 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 [] ).

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 .

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

( m has type int StringMap.t )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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