3

我在 OCaml 中创建了一个可变数据结构,但是当我访问它时,它给出了一个奇怪的错误,

这是我的代码

type vector = {a:float;b:float};;
type vec_store = {mutable seq:vector array;mutable size:int};;

let max_seq_length = ref 200;;

exception Out_of_bounds;;
exception Vec_store_full;;

let vec_mag {a=c;b=d} = sqrt( c**2.0 +. d**2.0);;


let make_vec_store() = 
    let vecarr = ref ((Array.create (!max_seq_length)) {a=0.0;b=0.0}) in
         {seq= !vecarr;size=0};;

当我在 ocaml 顶层执行此操作时

let x = make _ vec _store;;

然后尝试做x.size我得到这个错误

Error: This expression has type unit -> vec_store
       but an expression was expected of type vec_store

什么似乎是问题?我不明白为什么这不起作用。

谢谢,费萨尔

4

3 回答 3

12

make_vec_store是一个函数。当您说 时let x = make_vec_store,您将 x 设置为该函数,就像您编写时一样let x = 1,这将使 x 成为数字 1。您想要的是调用该函数的结果。根据make_vec_store的定义,它需要()(也称为“单位”)作为参数,所以你会写let x = make_vec_store ().

于 2009-10-27T07:44:18.000 回答
4

试试 x = make_vec_store()

于 2009-10-27T06:19:33.967 回答
2

As a follow up to the excellent answere provided. You can tell that your example line:

# let x = make_vec_store;;
val x : unit -> vec_store = <fun>

returns a function as the repl will tell you this. You can see from the output that x is of type <fun> that takes no parameters unit and returns a type vec_store.

Contrast this to the declaration

# let x = 1;;
val x : int = 1

which tells you that x is of type int and value 1.

于 2009-10-27T19:04:55.187 回答