ocaml

OCaml cant get array length


I'm trying to make shifting of array. But I'm getting syntax error on arr.length. (2nd line)

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;;

Solution

  • 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 *)
    

    So you should have

    let size = Array.length arr in
    let shifted = Array.make size 0 in
    . . .
    

    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
    

    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
    

    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.)