Syntax error in function to shift array by k

霸气de小男生 提交于 2019-12-11 17:05:33

问题


I'm trying to shift array by k to left. Here's my code. But I'm getting compile error on shifted;; line.

let shift_left (arr: array) (kk: int) =
    let size = Array.length arr in
        let k = kk mod size in
    let shifted = Array.make size 0 in

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

    shifted;;


let arr = [| 1; 2; 3; 4; 5; 6; 7; 8; 9; 10 |];;
let shifted = shift arr 4;;

Array.iter print_int arr;
print_string "\n";;

Array.iter print_int shifted;
print_string "\n";;

Here is what I getting in terminal:

$ ocamlc -o shift shift.ml

File "shift.ml", line 11, characters 1-8:
Error: Syntax error

回答1:


There are two compiler errors here:

  1. A syntax error between done and shifted. Because line breaks are not significant in OCaml, it will be parsed as done shifted;;, which looks like a function application, but is not valid since done is a keyword, not an identifier that might refer to a function. Use the sequence operator, ;, to evaluate two expressions in sequence.

  2. A type error: array is not a concrete type, it takes a type parameter specifying the type of value it contains. It should be int array in this case.



来源:https://stackoverflow.com/questions/57152344/syntax-error-in-function-to-shift-array-by-k

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!