OCaml无法获取数组长度

And*_* M. 0 ocaml

我是OCaml的新手,现在正尝试移动数组。但是我在上收到语法错误arr.length。(第二行)

let shift (arr : array) (k : int) =
    let size = arr.length;;
    let shifted = Array.make size 0;;

    for i = 0 to size- 1 do
        if i < k
        then shifted.(size- 1 - k + i) <- arr.(i);;
        else shifted.(i-k) <- arr.(i);;
    done

    shifted;;
Run Code Online (Sandbox Code Playgroud)

Jef*_*eld 5

Updated

There are a few problems with your code.

First, the ;; symbol really isn't part of OCaml syntax. It's used only in the interpreter (the toplevel or REPL) to tell the interpreter when to evaluate what you've typed so far. In ordinary source code it's only rarely used. Many people (including me) adopt a style where ;; is never used in source files.

By contrast, you are ending just about every line with ;;, which is guaranteed to cause syntax errors.

The way to define local variables of a function looks like this:

let var = expr in
(* rest of function comes here *)
Run Code Online (Sandbox Code Playgroud)

So you should have

let size = Array.length arr in
let shifted = Array.make size 0 in
. . .
Run Code Online (Sandbox Code Playgroud)

You should remove all your ;; tokens and add in as necessary.

In addition, you are using a kind of object-oriented syntax. But Arrays are not OO-style objects. To get the length of an array named arr:

Array.length arr
Run Code Online (Sandbox Code Playgroud)

Here's how it looks:

# let arr = Array.make 10 0;;
val arr : int array = [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]
# Array.length arr;;
- : int = 10
# Array.length [| "another"; "example" |];;
- : int = 2
Run Code Online (Sandbox Code Playgroud)

In other words, length is a function defined in the Array module. An OCaml array isn't an object (of the OO sort) and doesn't have methods.

(For future reference, methods of OCaml objects are referenced using #, as in object#method.)

  • 这不能解决语法错误,所有令人讨厌的`;;`都会导致这种错误。 (2认同)